![](/img/trans.png)
[英]Why do javascript literals act differently as their non-literal counterparts?
[英]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.stringify
和JSON.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.