我想把一个Html元素中的所有属性放入一个数组中:就像我有一个jQuery对象,它的html看起来像这样:
<span name="test" message="test2"></span>
现在,一种方法是使用描述为here的xml解析器,然后我需要知道如何获得我的对象的html代码。
另一种方法是使用jquery,但如何实现呢?属性的数量和名称是通用的。
谢谢
顺便说一下:我不能用document.getelementbyid或类似的东西访问元素。
发布于 2010-01-12 20:17:07
如果您只需要DOM属性,那么在元素本身上使用attributes
节点列表可能更简单:
var el = document.getElementById("someId");
for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){
arr.push(atts[i].nodeName);
}
请注意,这将仅使用属性名称填充数组。如果需要属性值,可以使用nodeValue
属性:
var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
}
发布于 2011-03-12 21:34:36
你可以使用这个简单的插件作为$('#some_id').getAttributes();
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
return attributes;
};
})(jQuery);
发布于 2012-07-20 18:04:12
简单:
var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
https://stackoverflow.com/questions/2048720
复制相似问题