【问题标题】:Iterating over element attributes with jQuery使用 jQuery 遍历元素属性
【发布时间】:2011-01-14 13:26:06
【问题描述】:

我知道可以使用 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() 方法相关的结果。提前致谢。

【问题讨论】:

标签: jquery xml dom traversal


【解决方案1】:

最好的方法是通过使用节点对象的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 的方法!
【解决方案2】:

看来您必须使用普通的老式香草 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);
    }
}

How to iterate through all attributes in an HTML element?

【讨论】:

  • 这并没有错。 attr() 是一种方便的方法。
【解决方案3】:

您能否使用 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 属性处理,check this blog post

【讨论】:

    【解决方案4】:

    怎么样?

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

    【讨论】:

      【解决方案5】:

      虽然您可以只使用标准的 DOM 元素属性 attributes,但它会在 IE6 中包含 every 属性(即使是那些未明确设置的属性)。作为替代方案,您可以限制设置的属性数量:

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

      【讨论】:

        【解决方案6】:

        我在这里发帖是因为我认为这可能会帮助其他看到此帖子的人像我一样解析 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());
            });
        });
        

        我很欣赏这可能无法完全回答最初的问题。不过,我希望它可以为其他访问者节省一些时间。

        问候

        【讨论】:

          【解决方案7】:

          创建了这个允许查看属性以及 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); 
              }); 
          }
          

          【讨论】:

            【解决方案8】:

            纯JS首先,你输入的xml不是valid,但是你可以通过/关闭子项标签来修复它

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

            【讨论】:

              猜你喜欢
              • 2018-04-13
              • 2013-04-11
              • 1970-01-01
              • 2018-06-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-10-04
              相关资源
              最近更新 更多