簡體   English   中英

如何將 javascript 字典轉換為 html 屬性列表?

[英]How can I convert a javascript dictionary to a list of html attributes?

我想采取這個:

var sneed = { feed: "and", seed: [ "formerly", "chucks" ] };

並產生這個:

feed="and" seed="formerly,chucks"

但是怎么做? 它需要在較舊的 javascript 版本中工作。

我的解決方案:

function arg( d = {} ) { 

        var sl = []; 
        for ( var key in d ) { 
                sl.push( key + '="' + d[key] + '"' );  
        } 
        return sl.join(" "); 
}

問題是,如果在任何字符串中找到任何 " ,這將很快失敗,這導致我詢問是否實際上有更簡單更直接的方法來執行此操作。

謝謝。

您可以通過將 & 和引號字符替換為相應的 HTML 實體來對字符串進行轉義,以安全准確地將其放入 HTML 屬性值中:

function escapeDoubleQuotedAttributeValue(str) {
    return str.replace(/&/g, "&")
              .replace(/"/g, """);
}

將您想要支持的任何對象轉換為字符串是一個單獨的問題。

function valueToString(value) {
    if (typeof value === 'string') {
        return value;
    }

    if (Object.prototype.toString.call(value) === '[object Array]') {
        return String(value);
    }

    throw new TypeError('Unsupported value');
}

function htmlAttributes(d) {
    var attributes = [];

    for (var key in d) {
        var stringValue = valueToString(d[key]);
        var escapedValue = escapeDoubleQuotedAttributeValue(stringValue);
        attributes.push(key + '="' + escapedValue + '"');
    }

    return attributes.join(" ");
}

檢查將值轉換為字符串是否會導致包含引號的值。 如果是這樣,請在 HTML 字符串中的屬性值周圍使用相反類型的引號。

如果兩者都包含,則使用雙引號作為分隔符,並將任何嵌入的雙引號替換為" .

 function arg(d = {}) { var sl = []; for (var key in d) { var value = d[key].toString(); var delim; if (value.includes('"') && value.includes("'")) { value = value.replace(/"/g, '"'); delim = '"'; } else if (value.includes('"')) { delim = "'"; } else { delim = '"'; } sl.push(key + '=' + delim + value + delim); } return sl.join(" "); } console.log(arg({ feed: "and", seed: [ "formerly", "chucks" ] })); console.log(arg({ feed: "and", seed: [ 'The "first"', "chucks" ] })); console.log(arg({ feed: "and", seed: [ "formerly", "chuc'ks" ] })); console.log(arg({ feed: "and", seed: [ 'for"erly', "chuc'ks" ] }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM