属性值自动插入双引号内

时间:2019-06-03 20:42:37

标签: javascript html dom

我想放置已创建的html节点。但是,当使用JS并插入div内时,单引号变为双引号。代码是:

function createHederaObject(params){
    let Hederaobject =  '<hedera-micropayment '
        for(var i in params){
            if(params.hasOwnProperty(i) && i!=='attrID'){
                Hederaobject += i +"= '"+ params[i] + "' , " + "\n";
            }
        }

        Hederaobject += '></hedera-micropayment>';
        console.log(Hederaobject);

        var body = document.getElementById(params['attrID']);
        body.innerHTML += Hederaobject;
        //console.log((Hederaobject))
        return Hederaobject;
        //callback(Hederaobject);
    }

我应该完全像这样:

     <hedera-micropayment submissionnode= '0.0.1761' ,
        time= '1559313345' ,
        type= 'article' ,
        memo= '1275,79' ,
        paymentserver= 'http://localhost:9090/' ,
        recipientlist= '[{ "to": "0.0.99", "tinybars": "4666667" }]' ,
        contentid= '79' ,
        extensionid= 'ligpaondaabclfigagcifobaelemiena' ,
        redirect= '{ "nonPayingAccount": "/insufficient-amount/", "noAccount": "/account-not-paired/", "homePage": "/" }' ,></hederamicropayment>

但是所有单引号都会被替换并变成这样:

    <hedera-micropayment data-submissionnode="0.0.1761" ,="" data-time="1559313345" data-type="article" data-memo="1275,79" data-paymentserver="http://localhost:9090/" data-recipientlist="[{ &quot;to&quot;: &quot;0.0.99&quot;, &quot;tinybars&quot;: &quot;4666667&quot; }]" data-contentid="79" data-extensionid="ligpaondaabclfigagcifobaelemiena" data-redirect="{ &quot;nonPayingAccount&quot;: &quot;/insufficient-amount/&quot;, &quot;noAccount&quot;: &quot;/account-not-paired/&quot;, &quot;homePage&quot;: &quot;/&quot; }"></hedera-micropayment>

在解析数据时产生了问题。

  data-recipientlist= '[{ "to": "0.0.99", "tinybars": "4666667" }]' ,

我必须具有相同的结构。

如何保持单引号不变。有任何想法吗 ?谢谢

1 个答案:

答案 0 :(得分:1)

这就是innerHTML的工作方式-具有属性的所有“字符串”节点都转换为DOM树-当您从中读取信息时(例如,通过浏览器“检查元素”,则DOM节点属性将转换为字符串)加上双引号)

document.body.innerHTML += `<div id='abc'>ABC</div>`;

console.log(abc);