使用jquery解析xml文件中元素的未知属性

时间:2022-12-01 10:55:30

Is it possible to get both the attribute name and the value of an element?

是否可以同时获取属性名称和元素的值?

Basically i want to get the name and the values of all attributes of a single element, in order to write them into a Javascript Object like this:

基本上我想获取单个元素的所有属性的名称和值,以便将它们写入Javascript对象,如下所示:

obj {
  key: "value",
  another_key: "another_value",
}

1 个解决方案

#1


4  

Using jQuery you can get name and values of all attributes for specific element like that:

使用jQuery,您可以获取特定元素的所有属性的名称和值,如下所示:

var obj = {}; // this object will hold key-value pairs of elem attributes
var attribs = $('#elem')[0].attributes;
for (var i = 0; i < attribs.length; i++) {
    obj[attribs[i].name] = attribs[i].value;
}

Remember to replace '#elem' with a valid selector for the element you want to get attributes from.

请记住将'#elem'替换为要从中获取属性的元素的有效选择器。

#1


4  

Using jQuery you can get name and values of all attributes for specific element like that:

使用jQuery,您可以获取特定元素的所有属性的名称和值,如下所示:

var obj = {}; // this object will hold key-value pairs of elem attributes
var attribs = $('#elem')[0].attributes;
for (var i = 0; i < attribs.length; i++) {
    obj[attribs[i].name] = attribs[i].value;
}

Remember to replace '#elem' with a valid selector for the element you want to get attributes from.

请记住将'#elem'替换为要从中获取属性的元素的有效选择器。