jquery - 使用 jQuery 遍历元素属性

标签 jquery xml 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>

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

$(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/

相关文章:

java.lang.ClassCastException : On custom composite component

JavaScript - 如果满足条件,则将内容包装在 DIV 中

javascript - 如何在 javascript 中鲁棒检测复选框值变化

javascript - 查明是否在单选按钮组中选择了单选按钮

javascript - 将跨度放在选定的文本上

javascript - 遍历 jquery 中的多个下拉列表

javascript - jQuery UI slider - 防止多个 handle 重叠

php - 将 CSS 类用于 JS 标记是一种不好的做法吗?

Jquery 按属性值选择不起作用 - 以防值中有空格

php - 在 Firefox(和其他浏览器)中以 XML 格式查看 PHP 文件输出