简体   繁体   English

将非文字JS对象存储在html属性中

[英]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. 我正在建立一个大型js库,我需要在html属性中存储一个非文字js对象的实例。 Since I cannot write the whole js file here, this is a similar code: 由于我无法在此处编写整个js文件,因此这是类似的代码:

<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? 我通过使用JQuery.data函数成功完成了此操作,但在这里不能使用jquery。如何存储实例? Thanks. 谢谢。

Attributes only store String's so you could achieve this by using JSON.stringify , and JSON.parse 属性仅存储String,因此您可以使用JSON.stringifyJSON.parse实现此JSON.stringify

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) 但是您也可以这样做(除非您实际上需要能够将所有内容都转换回HTML)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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