問題描述
我正在嘗試遍歷一個元素并獲取該元素的所有屬性以輸出它們,例如,一個標簽可能有 3 個或更多屬性,我不知道,我需要獲取這些屬性的名稱和值.我的想法是這樣的:
$(this).attr().each(function(index, element) {var name = $(this).name;var 值 = $(this).value;//用名稱和值做一些事情...});
誰能告訴我這是否可行,如果可行,正確的語法是什么?
attributes
屬性包含所有這些:
$(this).each(function() {$.each(this.attributes, function() {//this.attributes 不是一個普通的對象,而是一個數組//屬性節點,包含名稱和值如果(this.specified){console.log(this.name, this.value);}});});
<小時>
您還可以做的是擴展 .attr
以便您可以像 .attr()
一樣調用它來獲取所有屬性的普通對象:
(函數(舊) {$.fn.attr = 函數() {if(arguments.length === 0) {如果(this.length === 0){返回空值;}變量 obj = {};$.each(this[0].attributes, function() {如果(this.specified){obj[this.name] = this.value;}});返回對象;}返回 old.apply(this, arguments);};})($.fn.attr);
用法:
var $div = $("I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
Could anyone tell me if this is even possible, and if so what the correct syntax would be?
解決方案 The attributes
property contains them all:
$(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);
}
});
});
What you can also do is extending .attr
so that you can call it like .attr()
to get a plain object of all attributes:
(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);
Usage:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
這篇關于使用jQuery獲取元素的所有屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!