如何将html元素属性转换为JSON
问题描述:
我需要将属性对象转换为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"}
答
$("#delimiter")[0].attributes
返回属性节点的数组具有name
和value
财产,所以你需要,你可以做什么:
var attrs = {};
$("#delimiter")[0].attributes.forEach(function(element) {
attrs[element.name] = element.value;
});
为Element.attributes
here参见文档。
+0
我知道可以创建'每个'你能帮我创建'每个' –
答
你可以使用这个简单的插件作为$('#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);
更多的澄清也提供了HTML。 –