在jQuery中给定一个XML元素,如下所示:
$('<foo oy="vey" foo="bar" here="is" another="attribute" />')是否可以使用jQuery或普通旧式JavaScript来获取包含XML元素中所有属性名称的数组?我希望是这样的:
['oy','foo','here','another']发布于 2018-03-29 02:55:36
A)单个<Foo>元素
您是否需要单个元素的属性列表?
..。如果需要,您真的需要阵列吗?
简单的$('<foo ... />').get(0).attributes
...will 提供NamedNodeMap (object) of attributes
B)整个(XML)文档中的所有元素<Foo>
@Soufiane Hassou的答案是显示方法,但缺少内部循环...
您是否需要获取整个文档中某个元素(例如,Product元素)的所有可能的属性名称
var yourElements = document.getElementsByTagName('Foo'); //get all <Foo> elements
var listOfAttributeNames = []; //prepare empty array for attribute names
var attributeNameBuffer; //buffer for current attribute name in loop
//Loop all elements
for(var i = 0; i < yourElements.length ; ++i){
//Loop all attributes of a current element
for( k = 0 ; k < yourElements[i].attributes.length ; ++k ){
//Temporary store current attribute name
attributeNameBuffer = yourElements[i].attributes[k].name;
//First,
//test if the attribute name does not already exist in our array of names
if( listOfAttributeNames.indexOf(attributeNameBuffer) == -1 )
listOfAttributeNames.push( attributeNameBuffer ); //if not, add it
}
}
console.log(listOfAttributeNames); //display array of attributes in consolehttps://stackoverflow.com/questions/1705504
复制相似问题