Single quotes in data attribute containing json

前端 未结 5 1504
清酒与你
清酒与你 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: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);

提交回复
热议问题