使用jQuery迭代元素属性

前端之家收集整理的这篇文章主要介绍了使用jQuery迭代元素属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道单个属性可以用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文档,和其他地方通过谷歌,但没有运气。如果没有别的,我可能只是有麻烦排除与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 :-)
  });
});
原文链接:https://www.f2er.com/jquery/185399.html

猜你在找的jQuery相关文章