我想将 Html 元素中的所有属性放入一个数组中:就像我有一个 jQuery 对象,其 html 如下所示:
<span name="test" message="test2"></span>
现在一种方法是使用这里描述的 xml 解析器,但是我需要知道如何获取我的对象的 html 代码。
另一种方法是使用 jquery 来实现,但是如何实现呢?属性的数量和名称是通用的。
谢谢
顺便说一句:我无法使用 document.getelementbyid 或类似的东西访问该元素。
我想将 Html 元素中的所有属性放入一个数组中:就像我有一个 jQuery 对象,其 html 如下所示:
<span name="test" message="test2"></span>
现在一种方法是使用这里描述的 xml 解析器,但是我需要知道如何获取我的对象的 html 代码。
另一种方法是使用 jquery 来实现,但是如何实现呢?属性的数量和名称是通用的。
谢谢
顺便说一句:我无法使用 document.getelementbyid 或类似的东西访问该元素。
如果您只需要 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);
}
你可以使用这个简单的插件作为 $('#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);
简单的:
var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
因为在 IE7 中 elem.attributes 列出了所有可能的属性,不仅仅是当前的,我们必须测试属性值。此插件适用于所有主要浏览器:
(function($) {
    $.fn.getAttributes = function () {
        var elem = this, 
            attr = {};
        if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { 
            n = n.nodeName||n.name;
            v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
            if(v != undefined && v !== false) attr[n] = v
        })
        return attr
    }
})(jQuery);
用法:
var attribs = $('#some_id').getAttributes();
二传手和吸气剂!
(function($) {
    // Attrs
    $.fn.attrs = function(attrs) {
        var t = $(this);
        if (attrs) {
            // Set attributes
            t.each(function(i, e) {
                var j = $(e);
                for (var attr in attrs) {
                    j.attr(attr, attrs[attr]);
                }
            });
            return t;
        } else {
            // Get attributes
            var a = {},
                r = t.get(0);
            if (r) {
                r = r.attributes;
                for (var i in r) {
                    var p = r[i];
                    if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue;
                }
            }
            return a;
        }
    };
})(jQuery);
利用:
// Setter
$('#element').attrs({
    'name' : 'newName',
    'id' : 'newId',
    'readonly': true
});
// Getter
var attrs = $('#element').attrs();