循环遍历元素的数据属性 [英] Looping through element's data- attributes

查看:70
本文介绍了循环遍历元素的数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Per,

如何遍历HTML元素中的所有属性?

您将获得一般解决方案:

you get the general solution:

for (var i = 0; i < elem.attributes.length; i++) {
  var attrib = elem.attributes[i];
  if (attrib.specified) {
    alert(attrib.name + " = " + attrib.value);
  }
}

我如何才能使这个通用解决方案更具体提醒数据属性的值。

How would I make this general solution more specific to only alert the values of the data- attribute.

我需要regex attrib.name还是有更简单的方法?
以下是一些包含2个数据属性的示例HTML:

Would I need to regex attrib.name or is there a simpler way? Here is some sample HTML with 2 data- attributes:

<div id='universals' data-path='/zz/' data-load='1'></div>


推荐答案

在许多现代浏览器中,我们可以访问这些特殊属性通过节点对象上的 .dataset 成员。不幸的是,这还不是一个公认的标准,因此我们不认为这是在整个范围内采用的。幸运的是,在每个主要浏览器中都有部分支持,因为这些属性仍然可以使用常见方法访问,例如 getAttribute ,以及骑自行车 .attributes 列表。

In many modern browsers we have access to these special attributes via the .dataset member on the Node object. Unfortunately, this is not yet an accepted standard, and as such we don't see this being adopted all across the spectrum. Fortunately, there is partial support in every major browser in that these attributes can still be accessed using common methods like getAttribute, as well as by cycling over the .attributes list.

下面的代码显示了第二种方法:

The code below shows the second method:

// Reference to our element
var element = document.getElementById("universals"), attr;

// Cycle over each attribute on the element
for (var i = 0; i < element.attributes.length; i++) {
    // Store reference to current attr
    attr = element.attributes[i];
    // If attribute nodeName starts with 'data-'
    if (/^data-/.test(attr.nodeName)) {
        // Log its name (minus the 'data-' part), and its value
        console.log(
            "Key: " + attr.nodeName.replace(/^data-/, ''),
            "Val: " + attr.nodeValue
        );
    }
}

小提琴: http://jsfiddle.net/pGGqf/14/

你应该会发现这种方法适用于所有主流浏览器,甚至可以追溯到IE6。在支持 .dataset 成员的浏览器中,这也不是必需的。 .dataset 对象提供了一些额外的功能,因此如果您愿意,可以自由地检测它:

You should find that this approach will work in every major browser, even as far back as IE6. This isn't necessary, again, in browsers that support the .dataset member. There's a bit of extra functionality offered on the .dataset object, so you are free to feature-detect it if you like:

if (element.dataset) {
    // Browser supports dataset member
} else {
    // Browser does not support dataset member
}

这篇关于循环遍历元素的数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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