这是可以完成的许多方法的概述,供我自己和您参考:) 这些函数返回属性名称及其值的散列。
香草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 的 Vanilla 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=""
)。