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

Storing non-literal js object in an html attribute

本文关键字:文字 js 对象 存储 html 属性      更新时间:2023-09-26

我正在构建一个大的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。数据函数,但我不能在这里使用jquery .我如何存储实例?谢谢。

属性只存储字符串,所以您可以通过使用JSON.stringifyJSON.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);

但是你也可以这样做(除非你真的需要能够将所有内容转换回HTML)

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