Single quotes in data attribute containing json

前端 未结 5 1414
清酒与你
清酒与你 2021-02-12 21:06

Cosmetic question: I have a html element containing possible dimensions for some embedded images, these are stored as:

相关标签:
5条回答
  • 2021-02-12 21:52

    Try this and you can keep nicely formatted JSON in the attribute:

    $.parseJSON($('.inside').data('dimensions').replace(/'/g,"\""))
    
    0 讨论(0)
  • 2021-02-12 21:57

    Use " instead of " and ' instead of '.

    0 讨论(0)
  • 2021-02-12 21:57

    Another way is to use the function eval or create a new function. You can use either " or ' in your JSON and you don't need to put " around the keys in the JSON object.

    let el = document.getElementById('example');
    let person = (new Function(`return ${el.dataset.person}`))();
    console.log(person);
    person.age++;
    console.log(person.age);
    <div data-person="{name:'Natalie Portman',age:35}" id="example"></div>

    0 讨论(0)
  • 2021-02-12 22:01

    You can use &quot; instead of ". But quoting orgies are horrible (in HTML even more than in PHP) so better go with single-quoting your html attributes.

    BTW, you do not need to use .parseJSON - jQuery does that automatically if the data- attribute starts with { (actually, it's more complex - here's the regex it uses to test if it should be parsed as JSON: ^(?:\{.*\}|\[.*\])$).

    0 讨论(0)
  • The JSON specification stipulates that keys and (string) values be quoted with double-quotes.

    HTML attributes can be enclosed in either single or double quotes.

    Personally, I wouldn't fight it and just go with what causes the least amount of friction and is easiest for all to understand which in this case is to single quote the HTML attributes and use double-quotes inside the attribute value.

    0 讨论(0)
提交回复
热议问题