使用 jQuery 迭代元素属性 [英] Iterating over element attributes with jQuery

查看:25
本文介绍了使用 jQuery 迭代元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用 attr() 方法检索单个属性,但我正在尝试遍历元素的所有属性.对于上下文,我在一些 XML 上使用 jQuery...

I know individual attributes can be retrieved with the attr() method, but I'm trying to iterate over all of the attributes for an element. For context, I'm using jQuery on some XML...

<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>

我已经能够用...迭代项目了

I am already able to iterate over the items with...

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

但我希望能够获得每个项目"的属性数组,以便我可以遍历这些...

But I'd like to be able to get an array of attributes for each 'item' so I can then iterate over those...

例如

$(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() 方法相关的结果.提前致谢.

I've done some searching here, in the jQuery documentation, and elsewhere via Google but have had no luck. If nothing else, I may just be having trouble excluding results relating to the attr() method of the jQuery object. Thanks in advance.

推荐答案

最好的方法是通过使用节点对象的 attributes 属性直接使用它.与其他建议此方法的解决方案相比,我下面的解决方案的唯一区别是我将再次使用 .each 而不是传统的 js 循环:

The best way is to use the node object directly by using its attributes property. The only difference in my solution below compared to others suggesting this method is that i would use .each again instead of a traditional js loop:

$(xml).find('item').each(function() {
  $.each(this.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
     // do your magic :-)
  });
});

这篇关于使用 jQuery 迭代元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆