jQuery 循环遍历 data() 对象 [英] jQuery loop through data() object
本文介绍了jQuery 循环遍历 data() 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以遍历 data()
对象?
Is it possible to loop through a data()
object?
假设这是我的代码:
$('#mydiv').data('bar','lorem');
$('#mydiv').data('foo','ipsum');
$('#mydiv').data('cam','dolores');
我如何遍历这个?each()
可以用于这个吗?
How do I loop through this? Can each()
be used for this?
推荐答案
jQuery 将所有数据信息存储在 jQuery.cache 内部变量中.使用这个简单但有用的插件可以获得与特定对象关联的所有数据:
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);
});
您可以使用 matt b 的建议,但这是使用您现在拥有的方法来实现的方法.
You could just use matt b's suggestion but this is how to do it with what you have right now.
这篇关于jQuery 循环遍历 data() 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文