jQuery,将对象(而不是字符串属性)附加到元素 [英] jquery, attaching objects (instead of string attribute) to an element

查看:87
本文介绍了jQuery,将对象(而不是字符串属性)附加到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery构建DOM并用AJAX接收到的数据(数据类型= json)填充它.我还想将此数据存储为对象,并附加到特定的DOM元素. jQuery是否为此提供任何方法?我之所以要这样做,是因为最初只显示了部分数据.以后可能需要其他数据,具体取决于用户的操作.

I'm trying to build DOM with jQuery and fill it with data that is received with AJAX (data type = json). I'd like to also store this data as an object, attached to a specific DOM element. Does jQuery provide any method for this? The reason I want to do it is because only part of data is initially displayed; other data might be needed later, depending on user actions.

我尝试使用attr(),但是它存储的是字符串"[object Object]"而不是实际的对象:

I tried using attr(), but it stores a string "[object Object]" instead of an actual object:

var div = $('<div/>');
div.attr('foo', {bar: 'foobar'});
alert(div.attr('foo')); // gives "[object Object]"
alert(typeof div.attr('foo')); // gives "string"
alert(div.attr('foo').bar); // gives "undefined"

另一种方法是通过绕过" jQuery(div[0].foo = {bar: 'foobar'};),但如果jQuery恰好已经支持附加对象,这似乎是肮脏的解决方法".

Another way to do this would be by "bypassing" jQuery (div[0].foo = {bar: 'foobar'};), though this seems to be a "dirty workaround", if jQuery happens to already support attaching objects.

有什么想法吗?预先感谢!

Any ideas? Thanks in advance!

推荐答案

您可以使用 .data() 为此,就像这样:

You can use .data() for that purpose, like this:

div.data('foo', { bar: 'foobar' }); //sets it
var obj = div.data('foo'); //gets it

您可以在此处看到示例代码,只需将.attr()更改为.data() :

var div = $('<div/>');
div.data('foo', {bar: 'foobar'});
alert(div.data('foo')); // gives "[object Object]"
alert(typeof div.data('foo')); // gives "object"
alert(div.data('foo').bar); // gives "foobar"​​​​​​​​​​​​​​

这篇关于jQuery,将对象(而不是字符串属性)附加到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆