Javascript 在html属性中存储非文本js对象
我正在构建一个大的js库,需要在html属性中存储一个非文本js对象的实例。由于我无法在此处编写整个js文件,因此这是一个类似的代码:Javascript 在html属性中存储非文本js对象,javascript,html,Javascript,Html,我正在构建一个大的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());
<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>
函数abc(){this.foo=Math.random();…}//js对象
document.getElementById(“abc”).setAttribute(“数据abc”,新abc())//存储实例
log(document.getElementById(“abc”).getAttribute(“数据abc”).foo)//不知怎的,我没有定义
我通过使用JQuery.data函数成功地做到了这一点,但我不能在这里使用JQuery。我如何存储实例?谢谢。属性只存储字符串,因此您可以使用
JSON.stringify
和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);
但是,您也可以这样做(除非您确实需要能够将所有内容转换回HTML)
了解基本知识:HTML数据属性可以存储字符串,而
String.prototype
没有foo
属性,因此您会得到未定义的东西值得注意的是jQuery的数据函数实际上并不在DOM中存储东西。
document.getElementById("abc").abc = new abc();
console.log(document.getElementById("abc").abc.foo);