gpt4 book ai didi

javascript - 使用 jQuery 获取元素的所有属性

转载 作者:IT王子 更新时间:2023-10-29 02:39:24 26 4
gpt4 key购买 nike

我正在尝试遍历一个元素并获取该元素的所有属性以输出它们,例如,一个标签可能有 3 个或更多属性,我不知道,我需要获取这些属性的名称和值。我在想一些事情:

$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});

谁能告诉我这是否可行,如果可行,正确的语法是什么?

最佳答案

attributes 属性包含所有这些:

$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});

你还可以做的是扩展 .attr 这样你就可以像 .attr() 一样调用它来获得所有属性的普通对象:

(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}

var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}

return old.apply(this, arguments);
};
})($.fn.attr);

用法:

var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }

关于javascript - 使用 jQuery 获取元素的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14645806/

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