在单个元素上查找所有数据属性 [英] Find All Data Attributes on a Single Element

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

问题描述

有人知道一种快速有效的方法来从单个元素中获取所有数据属性吗?我意识到jQuerys .data()可以做到这一点,但是它不会给我使用.attr()设置的数据属性,除非我先使用.data()选择数据属性;另外,您不能通过使用.data()添加的数据属性来选择元素,这似乎很愚蠢.

Anyone know a quick and efficient way to grab all the data attributes from a single element? I realize that jQuerys .data() will do just that, however it will not give me data attributes set using .attr() UNLESS I first select the data attribute using .data(); Also, you can't select elements by data attributes that were added using .data(), which seems silly.

html

<div data-foo="bar"></div>

javascript

javascript

$("div").data();
//returns {foo:bar} good :)

$("div").attr("data-hello","world");
$("div").data()
//returns {foo:bar} no good :(

$("div[data-hello]");
//returns the div, all good :)

$("div").data("find","me");
$("div[data-find]");
//returns nothing, very bad

希望这能解释

推荐答案

您可以使用

You can use the dataset property in modern browsers(IE11+ only), but you can enhance the solution to use .attributes to support older browsers

var $in = $('input'),
    input = $in[0], //here input is a dom element reference
    dataMap = input.dataset;
//if dataset is not supported
if (typeof dataMap == 'undefined') {
    dataMap = {};
    $.each(input.attributes, function (key, attr) {
        var match = attr.name.match(/^data-(.+)/);
        if (match) {
            dataMap[match[0]] = attr.value;
        }
    })
}
$.each(dataMap, function (key, value) {
    console.log(key, value)
})

演示:小提琴

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

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