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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4187032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:17:42  来源:igfitidea点击:

Get list of data-* attributes using javascript / jQuery

javascriptjqueryhtmlattributes

提问by Shawn Chin

Given an arbitrary HTML element with zero or more data-*attributes, how can one retrieve a list of key-value pairs for the data.

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

E.g. given this:

例如,鉴于此:

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

I would like to be able to programmatically retrieve this:

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

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

Using jQuery (v1.4.3), accessing the individual bits of data using $.data()is simple if the keys are known in advance, but it is not obvious how one can do so with arbitrary sets of data.

使用 jQuery (v1.4.3),$.data()如果预先知道密钥,则访问单个数据位很简单,但如何使用任意数据集这样做并不明显。

I'm looking for a 'simple' jQuery solution if one exists, but would not mind a lower level approach otherwise. I had a go at trying to to parse $('#prod').attributesbut my lack of javascript-fu is letting me down.

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

update

更新

customdatadoes what I need. However, including a jQuery plugin just for a fraction of its functionality seemed like an overkill.

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

Eyeballing the source helped me fix my own code (and improved my javascript-fu).

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

Here's the solution I came up with:

这是我想出的解决方案:

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;
}

update 2

更新 2

As demonstrated in the accepted answer, the solution is trivial with jQuery (>=1.4.4). $('#prod').data()would return the required data dict.

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

采纳答案by Yi Jiang

Actually, if you're working with jQuery, as of version 1.4.31.4.4 (because of the bug as mentioned in the comments below), data-*attributes are supported through .data():

实际上,如果您正在使用 jQuery,那么从版本开始 1.4.31.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 1.4.3 开始,HTML 5data-属性将自动拉入 jQuery 的数据对象。

请注意,当 JavaScript 值转换为其关联值(这包括布尔值、数字、对象、数组和 null)时,字符串保持不变。的data-属性被拉到在第一时间中的数据属性被访问,然后不再访问或突变的(所有数据值然后被存储在内部的jQuery)。

The jQuery.fn.datafunction will return all of the data-attribute inside an object as key-value pairs, with the key being the part of the attribute name after data-and the value being the value of that attribute after being converted following the rules stated above.

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

I've also created a simple demo if that doesn't convince you: http://jsfiddle.net/yijiang/WVfSg/

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

回答by gilly3

A pure JavaScript solution ought to be offered as well, as the solution is not difficult:

还应该提供纯 JavaScript 解决方案,因为该解决方案并不难:

var a = [].filter.call(el.attributes, function(at) { return /^data-/.test(at.name); });

This gives an array of attribute objects, which have nameand valueproperties:

这给出了一个属性对象数组,它们具有namevalue属性:

if (a.length) {
    var firstAttributeName = a[0].name;
    var firstAttributeValue = a[0].value;
}

Edit:To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:

编辑:更进一步,您可以通过迭代属性并填充数据对象来获取字典:

var data = {};
[].forEach.call(el.attributes, function(attr) {
    if (/^data-/.test(attr.name)) {
        var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function (
Object.keys(data).forEach(function(key) {
    var attrName = "data-" + key.replace(/[A-Z]/g, function(
var a = [].filter.call(el.attributes, at => /^data-/.test(at.name));
) { return "-" +
var attributes = element.dataset
.toLowerCase(); }); el.setAttribute(attrName, data[key]); });
, ) { return .toUpperCase(); }); data[camelCaseName] = attr.value; } });

You could then access the value of, for example, data-my-value="2"as data.myValue;

然后,您可以访问例如data-my-value="2"as的值data.myValue

jsfiddle.net/3KFYf/33

jsfiddle.net/3KFYf/33

Edit:If you wanted to set data attributes on your element programmatically from an object, you could:

编辑:如果您想从对象以编程方式在元素上设置数据属性,您可以:

var cat = element.dataset.cat

jsfiddle.net/3KFYf/34

jsfiddle.net/3KFYf/34

EDIT:If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:

编辑:如果你使用 babel 或 TypeScript,或者只为 es6 浏览器编码,这是一个使用 es6 箭头函数的好地方,并稍微缩短代码:

var dataset = el.dataset; // as you asked in the question

回答by Felix Kling

Have a look here:

看看这里

If the browser also supports the HTML5 JavaScript API, you should be able to get the data with:

如果浏览器还支持 HTML5 JavaScript API,您应该能够通过以下方式获取数据:

var data = Object.keys(el.dataset);

or

或者

Object.keys(el.dataset).map(function(key){ return el.dataset[key];});
// or the ES6 way: Object.keys(el.dataset).map(key=>{ return el.dataset[key];});

Oh, but I also read:

哦,但我也读到:

Unfortunately, the new dataset property has not yet been implemented in any browser, so in the meantime it's best to use getAttributeand setAttributeas demonstrated earlier.

不幸的是,新的数据集属性尚未在任何浏览器中实现,因此同时最好使用getAttributesetAttribute如前所述。

It is from May 2010.

这是从 2010 年 5 月开始的。



If you use jQuery anyway, you might want to have a look at the customdataplugin. I have no experience with it though.

如果您无论如何都使用 jQuery,您可能需要查看customdata插件。我没有这方面的经验。

回答by Sergio

As mentioned above modern browsershave the The HTMLElement.datasetAPI.
That API gives you a DOMStringMap, and you can retrieve the list of data-*attributes simply doing:

如上所述,现代浏览器具有HTMLElement.datasetAPI。
该 API 为您提供DOMStringMap,您data-*只需执行以下操作即可检索属性列表:

$.fn.info = function () {
    var data = {};
    [].forEach.call(this.get(0).attributes, function (attr) {
        if (/^data-/.test(attr.name)) {
            var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function (
var data = element.dataset;
, ) { return .toUpperCase(); }); data[camelCaseName] = attr.value; } }); return data; }

you can also retrieve a array with the data-property's key names like

您还可以使用data-属性的键名检索数组,例如

    $.each($('#myEl').data(), function(key, value) {
        console.log(key);
        console.log(value);
    });

or map its values by

或映射其值

var model = $(".model");

var ul = $("<ul>").appendTo("body");

$(model).each(function(index, item) {
  ul.append($(document.createElement("li")).text($(this).text()));
  $.each($(this).data(), function(key, value) {
    ul.append($(document.createElement("strong")).text(key + ": " + value));
    ul.append($(document.createElement("br")));
  }); //inner each
  ul.append($(document.createElement("hr")));
}); // outer each

/*print html*/
var htmlString = $("ul").html();
$("code").text(htmlString);

and like this you can iterate those and use them without the need of filtering between all attributes of the element like we needed to do before.

像这样,您可以迭代它们并使用它们,而无需像我们之前需要的那样在元素的所有属性之间进行过滤。

回答by PHPst

or convert gilly3's excellent answer to a jQuery method:

或 convertgilly3对 jQuery 方法的出色回答:

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/prism.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/themes/prism-okaidia.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="demo"></h1>

<ul>
  <li class="model" data-price="45$" data-location="Italy" data-id="1234">Model 1</li>
  <li class="model" data-price="75$" data-location="Israel" data-id="4321">Model 2</li> 
  <li class="model" data-price="99$" data-location="France" data-id="1212">Model 3</li> 
</ul>

<pre>
<code class="language-html">
  
</code>
</pre>

<h2>Generate list by code</h2>
<br>

Using: $('.foo').info();

使用:$('.foo').info();

回答by lychi

You should be get the data through the dataset attributes

您应该通过数据集属性获取数据

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
        if(element.attributes[i].name.includes("data-")){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value
        }
        i++;
    }

    return elementAttributes;

}

datasetis useful tool for get data-attribute

数据集是获取数据属性的有用工具

回答by Andrew

You can just iterate over the data attributes like any other object to get keys and values, here's how to do it with $.each:

您可以像任何其他对象一样遍历数据属性以获取键和值,以下是如何使用$.each

##代码##

回答by Ezra Siton

I use nested each- for me this is the easiest solution (Easy to control/change "what you do with the values - in my example output data-attributes as ul-list) (Jquery Code)

我使用嵌套每个- 对我来说这是最简单的解决方案(易于控制/更改“你对值的处理 - 在我的示例中输出数据属性为ul-list)(Jquery代码)

##代码## ##代码##

Codepen: https://codepen.io/ezra_siton/pen/GRgRwNw?editors=1111

代码笔:https://codepen.io/ezra_siton/pen/GRgRwNw ?editors =1111

回答by Jmorel88

One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

查找所有数据属性的一种方法是使用element.attributes. 使用.attributes,您可以遍历所有元素属性,过滤掉包含字符串“data-”的项目。

##代码##