开发者

jquery, attaching objects (instead of string attribute) to an element

开发者 https://www.devze.com 2022-12-29 22:29 出处:网络
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 jQuer

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 n开发者_开发知识库eeded later, depending on user actions.

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"

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!


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

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

You can see your example code working here just by changing .attr() to .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"​​​​​​​​​​​​​​


I suggest that you use the data method of the jQuery object. This way you can attach custom data (JSON) to the respective DOM element. Here is sample code:

jQuery("div").data("key", /* JSON object */);

later you can get the associated data the following way:

var data = jQuery("div").data("key");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号