繁体   English   中英

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

[英]Storing non-literal js object in an html attribute

我正在建立一个大型js库,我需要在html属性中存储一个非文字js对象的实例。 由于我无法在此处编写整个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>

我通过使用JQuery.data函数成功完成了此操作,但在这里不能使用jquery。如何存储实例? 谢谢。

属性仅存储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);

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