以下是多种实现方式的概述,供我和您参考 :) 这些函数返回属性名称及其值的哈希表。
原生JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
使用Array.reduce进行原生JavaScript编程
适用于支持ES 5.1(2011)的浏览器。需要IE9+,无法在IE8中运行。
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
该函数需要一个 jQuery 对象,而不是 DOM 元素。
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
下划线
同样适用于lodash。
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
比Underscore版本更加简洁,但仅适用于lodash,不适用于Underscore。需要IE9+,在IE8中存在缺陷。赞扬@AlJey提供的信息。
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
测试页面
在JS Bin上,有一个实时测试页面,涵盖了所有这些功能。测试包括布尔属性(hidden
)和枚举属性(contenteditable=""
)。
$().attr()
。 - Alexanderattributes
集合包含旧版 IE 中的所有可能属性,而不仅限于在 HTML 中已指定的属性。您可以通过使用每个属性的specified
属性来过滤属性列表来解决此问题。 - Tim Down.attr()
方法非常好且预期的功能。奇怪的是,jQuery 没有包含它。 - ivkremerthis[0].attributes
作为数组来访问它? - Vishal