gpt4 book ai didi

javascript - 查找单个元素的所有数据属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:24 24 4
gpt4 key购买 nike

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

html

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

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

希望这能解释

最佳答案

您可以使用 dataset现代浏览器中的属性(仅限 IE11+),但您可以增强解决方案以使用 .attributes支持旧浏览器

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

演示:Fiddle

关于javascript - 查找单个元素的所有数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com