我正在JavaScript一个HTML页面动态构建并设置带有文本的属性。
有时文本是一个简单的字符串,有时我有一个使用JSON.stringify()将其另存为字符串的JSON对象。

 $("<a id=\"ftr\" myData=\"" + myString + "\" </a>").appendTo(myDiv);


然后,我提取该属性:

var temp = $(this).attr("myData"); // inside loop , $(this) refers to the correct link

当是这样的简单文本时,一切正常。

 <a id="ftr" myData="text test"></a>


但是当提取JSON对象时,我只能得到以下结果:"[{"

 <a id="ftr" myData="[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]></a>


如何提取JSON格式的完整对象?

最佳答案

正确使用引号

<a id="ftr" myData='[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]'></a>


我也建议您使用data- *属性,例如

<a id="ftr" data-mydata='[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]'></a>


然后您可以使用.data()获取

var temp = $(this).data("mydata");


DEMO

07-24 09:44
查看更多