javascript - 使用 javascript/jQuery 获取 data-* 属性列表

标签 javascript jquery html attributes

给定一个具有零个或多个 data-* 属性的任意 HTML 元素,如何检索数据的键值对列表。

例如鉴于此:

<div id='prod' data-id='10' data-cat='toy' data-cid='42'>blah</div>

我希望能够以编程方式检索此内容:

{ "id":10, "cat":"toy", "cid":42 }

使用 jQuery (v1.4.3),如果事先知道 key ,使用 $.data() 访问数据的各个位很简单,但如何做到这一点并不明显使用任意数据集。

我正在寻找一种“简单”的 jQuery 解决方案(如果存在),但不介意其他较低级别的方法。我尝试解析 $('#prod').attributes 但我缺乏 javascript-fu 让我失望了。

更新

customdata做我需要的。然而,仅仅为它的一小部分功能包括一个 jQuery 插件似乎有点过头了。

查看源代码帮助我修复了自己的代码(并改进了我的 javascript-fu)。

这是我想出的解决方案:

function getDataAttributes(node) {
    var d = {}, 
        re_dataAttr = /^data\-(.+)$/;

    $.each(node.get(0).attributes, function(index, attr) {
        if (re_dataAttr.test(attr.nodeName)) {
            var key = attr.nodeName.match(re_dataAttr)[1];
            d[key] = attr.nodeValue;
        }
    });

    return d;
}

更新 2

正如接受的答案所示,使用 jQuery (>=1.4.4) 的解决方案很简单。 $('#prod').data() 将返回所需的数据字典。

最佳答案

实际上,如果您使用 jQuery,从版本 1.4.3 1.4.4 开始(由于下面评论中提到的错误),data-* .data() 支持属性:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

jQuery.fn.data函数将返回所有 data-对象内部的属性作为键值对,键是属性名称在 data- 之后的部分该值是该属性在按照上述规则转换后的值。

如果这不能说服您,我还创建了一个简单的演示:http://jsfiddle.net/yijiang/WVfSg/

关于javascript - 使用 javascript/jQuery 获取 data-* 属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4187032/

相关文章:

javascript - 通过php加载HTML表单然后使用JQuery提交表单

jquery - 如何获取 iframe 中的窗口宽度?

html - 两个 div 彼此相邻,当文本在另一个中时,一个向下移动

html - 如何在 iOS 中检测 UIWebView 中音频的播放状态?

Javascript 简单 UDF

javascript - 工具提示图像而不是文本

javascript - 转义单引号 javascript

jquery - 使用 jQuery 为多选的某些选项着色的错误

javascript - 由于 Windows chrome 中的打印功能导致网站出现故障

javascript - 帧间 SOP - Chrome 扩展