以下是可以完成的许多方法的概述,供我自己参考以及您的参考:) 这些函数返回属性名称及其值的哈希值。
香草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 的香草 JS
适用于支持 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;
}, {} );
}
罗达什
比 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=""
)。