简体   繁体   中英

Storing non-literal js object in an html attribute

I'm building a big js library and I need to store an instance of a non-literal js object in an html attribute. Since I cannot write the whole js file here, this is a similar code:

<div id="abc"></div>
<script>
  function abc(){this.foo = Math.random(); ... } //The js object
  document.getElementById("abc").setAttribute("data-abc",new abc()); //Store the instance
  console.log(document.getElementById("abc").getAttribute("data-abc").foo); //Somehow I get undefined
</script>

I succeed to do it by using the JQuery.data function but I cannot use jquery here..How can I store the instance? Thanks.

Attributes only store String's so you could achieve this by using JSON.stringify , and JSON.parse

function abc(){this.foo = Math.random();}
document.getElementById("abc").setAttribute("data-abc",JSON.stringify(new abc()));
console.log(JSON.parse(document.getElementById("abc").getAttribute("data-abc")).foo);

however you could also just do this (unless you actually need to be able to convert everything back to HTML)

document.getElementById("abc").abc = new abc();
console.log(document.getElementById("abc").abc.foo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM