使用jQuery迭代元素属性

前端之家收集整理的这篇文章主要介绍了使用jQuery迭代元素属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道单个属性可以用attr()方法检索,但我试图迭代一个元素的所有属性。对于上下文,我在一些XML上使用jQuery …
  1. <items>
  2. <item id="id123" name="Fizz" value="Buzz" type="xyz">
  3. <subitem name="foo">
  4. <subitem name="bar">
  5. </item>
  6. <item id="id456" name="Bizz" value="Bazz" type="abc">
  7. <subitem name="meh">
  8. <subitem name="hem">
  9. </item>
  10. </items>

我已经能够迭代的项目与…

  1. $(xml).find('item').each(function() {
  2. // Do something to each item here...
  3. });

但我想能够得到一个属性数组的每个’项目’,所以我可以重复这些…

例如

  1. $(xml).find('item').each(function() {
  2. var attributes = $(this).attributes(); // returns an array of attributes?
  3. for (attribute in attributes) {
  4. // Do something with each attribute...
  5. }
  6. });

我在这里做了一些搜索,在jQuery文档,和其他地方通过谷歌,但没有运气。如果没有别的,我可能只是有麻烦排除与jQuery对象的attr()方法相关的结果。提前致谢。

解决方法

最好的方法是通过使用其attributes属性直接使用节点对象。在我的解决方案下面的唯一区别与其他人建议这种方法是,我会再次使用.each而不是传统的js循环:
  1. $(xml).find('item').each(function() {
  2. $.each(this.attributes,function(i,attrib){
  3. var name = attrib.name;
  4. var value = attrib.value;
  5. // do your magic :-)
  6. });
  7. });

猜你在找的jQuery相关文章