2017-07-30 53 views
-1

我需要将属性对象转换为JSON类型,但属性对象是一种魔法。如何将html元素属性转换为JSON

代码:

var attrs = $("#delimiter")[0].attributes; 
console.log(attrs); 
console.log(attrs["id"]); 
console.log(JSON.stringify(attrs)); 

结果:

{0: id, 1: title, length: 2} 
id=​"delimiter" 
{"0":{},"1":{}} 

我需要导致这样的:

{"id" : "foo", "title" : "some title"} 
+0

更多的澄清也提供了HTML。 –

回答

1

$("#delimiter")[0].attributes返回属性节点的数组具有namevalue财产,所以你需要,你可以做什么:

var attrs = {}; 
$("#delimiter")[0].attributes.forEach(function(element) { 
    attrs[element.name] = element.value; 
}); 

Element.attributeshere参见文档。

+0

我知道可以创建'每个'你能帮我创建'每个' –

1

你可以使用这个简单的插件作为$('#delimiter').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);