Get all attributes of an element using jQuery(使用jQuery获取元素的所有属性)
问题描述
我正在尝试遍历一个元素并获取该元素的所有属性以输出它们,例如,一个标签可能有 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获取元素的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用jQuery获取元素的所有属性


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01