the*_*ear 46 xml jquery dom traversal
我知道可以使用该attr()方法检索单个属性,但我正在尝试迭代元素的所有属性.对于上下文,我在一些XML上使用jQuery ...
<items>
<item id="id123" name="Fizz" value="Buzz" type="xyz">
<subitem name="foo">
<subitem name="bar">
</item>
<item id="id456" name="Bizz" value="Bazz" type="abc">
<subitem name="meh">
<subitem name="hem">
</item>
</items>
Run Code Online (Sandbox Code Playgroud)
我已经能够用...迭代这些项目了...
$(xml).find('item').each(function() {
// Do something to each item here...
});
Run Code Online (Sandbox Code Playgroud)
但我希望能够为每个"项目"获取一系列属性,以便我可以迭代这些...
例如
$(xml).find('item').each(function() {
var attributes = $(this).attributes(); // returns an array of attributes?
for (attribute in attributes) {
// Do something with each attribute...
}
});
Run Code Online (Sandbox Code Playgroud)
我已经在jQuery文档中进行了一些搜索,在谷歌的其他地方进行了搜索,但没有运气.如果没有别的,我可能只是在排除与attr()jQuery对象的方法相关的结果时遇到问题.提前致谢.
pro*_*son 104
最好的方法是使用其attributes属性直接使用节点对象.与其他人相比,我的解决方案与.each传统的js循环相比,唯一的区别在于我将再次使用这种方法:
$(xml).find('item').each(function() {
$.each(this.attributes, function(i, attrib){
var name = attrib.name;
var value = attrib.value;
// do your magic :-)
});
});
Run Code Online (Sandbox Code Playgroud)
Jur*_*nka 10
看来你必须使用普通的老香草javascript:
for (var i = 0; i < elem.attributes.length; i++) {
var attrib = elem.attributes[i];
if (attrib.specified == true) {
console.log(attrib.name + " = " + attrib.value);
}
}
Run Code Online (Sandbox Code Playgroud)