jQuery遍历data()对象 [英] jQuery loop through data() object

查看:730
本文介绍了jQuery遍历data()对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以遍历data()对象?

假设这是我的代码:

$('#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屋!

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