将JSON对象存储在HTML jQuery的数据属性中 [英] Store JSON object in data attribute in HTML jQuery
问题描述
我使用 data -
方法在HTML标记中存储数据,如下所示:
I am storing data using the data-
approach in a HTML tag like so:
<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>
然后,我在回调中检索数据,如下所示:
I am then retrieving the data in a callback like this:
$(this).data('imagename');
这很好。我所坚持的是试图保存对象而不仅仅是它的一个属性。我尝试这样做:
That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:
<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>
然后我尝试访问名称属性,如下所示:
Then I tried to access the name property like this:
var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);
日志告诉我 undefined
。因此,我似乎可以在 data -
属性中存储简单字符串,但无法存储JSON对象...
The log tells me undefined
. So it seems like I can store simple strings in the data-
attributes but I can't store JSON objects...
I've also tried to use this kid of syntax with no luck:
<div data-foobar='{"foo":"bar"}'></div>
{ foo 的: 酒吧}'>< / DIV>
Any idea on how to store an actual object in the HTML tag using the data-
approach?
有关如何使用存储HTML标记中的实际对象的任何想法data -
方法?
推荐答案
它实际上不会被存储在html中,但如果您使用的是jquery.data,则无论如何都会将其抽象出来。
it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.
要获取JSON,请不要解析它,只需调用:
To get the JSON back don't parse it, just call:
var getBackMyJSON = $('#myElement').data('key');
如果您得到 [Object Object]
而不是直接的JSON,只需通过数据键访问您的JSON即可:
If you are getting [Object Object]
instead of direct JSON, just access your JSON by the data key:
var getBackMyJSON = $('#myElement').data('key').key;
这篇关于将JSON对象存储在HTML jQuery的数据属性中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!