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...
});

但我希望能够为每个“项目”获取一组属性,这样我就可以遍历那些......

例如

$(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 进行了一些搜索,但没有运气。如果不出意外,我可能只是无法排除与attr()jQuery 对象的方法相关的结果。提前致谢。

4

8 回答 8

109

最好的方法是通过使用节点对象的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 :-)
  });
});
于 2010-02-08T21:27:44.110 回答
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 元素中的所有属性?

于 2010-02-08T21:23:00.127 回答
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 属性处理,请查看此博客文章

于 2010-02-08T21:24:44.087 回答
1

怎么样?

$(xml).find('item').each(function() {
  var attributes = $(this)[0].attributes;
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});
于 2010-02-08T21:24:15.150 回答
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
    }
  })
});
于 2010-02-08T21:28:56.027 回答
1

我在这里发帖是因为我认为它可能会帮助其他到达此帖子的人希望像我一样解析 xml 文件。

我正在寻找一种遍历与 theracoonbear 的文件结构非常相似的 xml 文件并将结果存储在数组中的方法,并遇到了这个帖子。

我查看了 prodigitalson 的代码,但我根本无法使用这种语法——firefox 在一行中抱怨说:

 $.each(this.attributes, function(i, attrib){

this.attributes

不是定义的函数。 我很确定这个错误完全是我的。但是我花了几个小时试图让这个工作并且失败了

对我有用的是(我的标签名称是会话而不是项目):-

$(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());
    });
});

我很欣赏这可能无法完全回答原始问题。但是,我希望它可以为其他访问者节省一些时间。

问候

于 2012-09-10T17:43:12.293 回答
1

创建了这个允许查看属性以及innearHtml的通用函数:

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); 
    }); 
}
于 2016-07-05T19:58:18.947 回答
-1

纯 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}`)
}));

于 2019-01-25T13:10:22.550 回答