我知道可以使用 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>
我已经能够使用...迭代项目
$(xml).find('item').each(function() {
// Do something to each item here...
});
但我希望能够为每个“项目”获取一组属性,这样我就可以遍历这些...
例如
$(xml).find('item').each(function() {
var attributes = $(this).attributes(); // returns an array of attributes?
for (attribute in attributes) {
// Do something with each attribute...
}
});
我在这里、jQuery 文档和其他地方通过 Google 进行了一些搜索,但没有成功。如果不出意外,我可能只是无法排除与 jQuery 对象的 attr()
方法相关的结果。提前致谢。
最佳答案
最好的方法是通过使用节点对象的 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 :-)
});
});
关于jquery - 使用 jQuery 遍历元素属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224933/