这里是可以完成的许多方法的概述,供我自己参考以及您的参考:) 这些函数返回属性名称及其值的散列。
原版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;
}, {} );
}
lodash
比Underscore版本更简洁,但只适用于lodash,不适用于Underscore。需要 IE9+,在 IE8 中有问题。感谢@AlJey for that one。
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
测试页面
在JS Bin,有一个live test page 涵盖了所有这些功能。测试包括布尔属性(hidden)和枚举属性(contenteditable="")。