使用jQuery迭代元素属性

51

我知道可以使用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...
});

但我希望能够获取每个“item”的属性数组,以便可以对其进行迭代...

例如:

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


1
请参见http://stackoverflow.com/questions/1705504/javascript-jquery-how-do-i-get-an-array-of-all-attributes-in-an-xml-element。 - Roatin Marth
8个回答

110

最好的方法是直接使用节点对象,并使用其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 :-)
  });
});

@prodigalson:感谢你提出这种索引 foreach 的方法! - Robin Maben

12

看起来你需要使用普通的纯javascript:

for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    if (attrib.specified == true) {
        console.log(attrib.name + " = " + attrib.value);
    }
}

如何遍历HTML元素中的所有属性?


并且这没有任何问题。attr()是一个方便的方法。 - BC.

4
你能否使用get()函数从jQuery包装器中获取DOM元素,然后迭代DOM属性?
var node = $(myStuff).get(0);
if (node.attributes.length) {

    for (var length = attrs.length, i = 0; i < length; i++) {
        if (attrs[i].specified) {

        }
    }
}

如果需要更加强大的DOM属性处理,可以查看这篇博客文章


1
我已经创建了这个通用函数,可以查看属性和innerHtml内容:
function findByAll(toLookFor, lookInText) { 
    return $('*').filter(function() { 
        return Array.prototype.some.call(this.attributes, function(attr) {
            return attr.value.indexOf(toLookFor) >= 0; 
        }) || (lookInText && $(this).text().indexOf(toLookFor) >= 0); 
    }); 
}

1

怎么样?

$(xml).find('item').each(function() {
  var attributes = $(this)[0].attributes;
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});

1

虽然您可以使用标准的DOM元素属性attributes,但在IE6中它将包括每个属性(即使没有明确设置)。作为替代方案,您可以限制您设置的属性数量:

var use_attributes = ['id','name','value','type'];
$(xml).find('item').each(function() {
  var $item = $(this);

  $.each( use_attributes, function(){
    if($item.attr( this )){
      // Act on the attribute here. 
      // `this` = attribute name
      // $item.attr( this ) = attribute value
    }
  })
});

1
我在这里发布帖子,因为我认为它可能会帮助到其他人,他们像我一样需要解析xml文件。
我正在寻找一种遍历具有与theracoonbear的fle非常相似结构的xml文件并将结果存储在数组中的方法,并偶然发现了这篇文章。
我查看了prodigitalson的代码,但我无法让这个语法工作-火狐浏览器抱怨在以下行中:
 $.each(this.attributes, function(i, attrib){

那个

this.attributes

未定义的函数。

我非常确定错误完全是我的问题,但我已经花费了数小时尝试让它工作,但失败了。

对我有用的是(其中我的标签名称为session而不是item):

$(xml_Data).find("session").each(function() {
    console.log("found session");
    $(this).children().each(function(){
     console.log("found child " + this.tagName);
     console.log("attributes" + $(this).text());
    });
});

我明白这可能并不完全回答了原来的问题。但是,我希望这可以为其他访问者节省一些时间。

此致敬礼


-1

Pure JS 首先,您的输入xml不有效,但您可以通过关闭子项标签/来修复它。

let items = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));

let 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>`;

let items  = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接