Javascript 如何将html元素属性转换为JSON
我需要将属性对象转换为JSON类型,但属性对象是一个魔术 代码:Javascript 如何将html元素属性转换为JSON,javascript,jquery,html,attributes,Javascript,Jquery,Html,Attributes,我需要将属性对象转换为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":{}} 结果: var attrs = $("#delimiter
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":{}}
结果:
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]。attributes
返回一个包含名称
和值
属性的属性节点数组,因此要执行所需操作,可以执行以下操作:
var attrs = {};
$("#delimiter")[0].attributes.forEach(function(element) {
attrs[element.name] = element.value;
});
请参阅元素的文档。attributes
$(“#分隔符”)[0]。attributes
返回一个包含名称和值的属性节点数组,因此要执行所需操作,可以执行以下操作:
var attrs = {};
$("#delimiter")[0].attributes.forEach(function(element) {
attrs[element.name] = element.value;
});
请参阅元素.attributes的文档
您可以使用这个简单的插件作为$(“#分隔符”).getAttributes()代码>
您可以使用这个简单的插件作为$('#分隔符').getAttributes()代码>
也提供html以获得更多澄清。也提供html以获得更多澄清。我知道可以使用“each”创建您可以帮助我创建而不使用“each”吗?我知道可以使用“each”创建您可以帮助我创建而不使用“each”吗