jQuery loop through data() object

Is it possible to loop through a data() object?

Suppose this is my code:

$('#mydiv').data('bar','lorem');  
$('#mydiv').data('foo','ipsum');  
$('#mydiv').data('cam','dolores');

How do I loop through this? Can each() be used for this?


jQuery stores all the data information in the jQuery.cache internal variable. It is possible to get all the data associated with a particular object with this simple but helpful plugin:

jQuery.fn.allData = function() {
    var intID = jQuery.data(this.get(0));
    return(jQuery.cache[intID]);
};

With this in place, you can do this:

$('#myelement').data('test1','yay1')
               .data('test2','yay2')
               .data('test3','yay3');

$.each($('#myelement').allData(), function(key, value) {
    alert(key + "=" + value);
});

You could just use matt b's suggestion but this is how to do it with what you have right now.


$.each($.data(this), function(i, e) {
   alert('name='+ i + ' value=' +e);
});

这将迭代'this'元素的数据对象中的每个属性。


I don't think that there is any function that gives you all of the "keys" of the data that has been added with the data() function, but instead, why not put all of your data into the function under an object / map?

something like this:

var container = new Object();
container.bar = "lorem";
container.foo = "ipsum";
container.cam = "dolores";
$("mydiv").data("container", container);

and then when you want to read the data / iterate through it:

var blah = $("mydiv").data("container");
for(key in blah) {
    var value = blah[key];
    //do whatever you want with the data, such as:
    console.log("The value of ", key, " is ", value);
}
链接地址: http://www.djcxy.com/p/40676.html

上一篇: 对象和数组的ECMAScript5深层副本

下一篇: jQuery通过data()对象循环