使用 jQuery 迭代元素属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2224933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:03:45  来源:igfitidea点击:

Iterating over element attributes with jQuery

jqueryxmldomtraversal

提问by theraccoonbear

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

我知道可以使用该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>

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

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

e.g.

例如

$(xml).find('item').each(function() {
  var attributes = $(this).attributes(); // returns an array of attributes?
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});

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.

我已经在这里、jQuery 文档和其他地方通过 Google 进行了一些搜索,但没有运气。如果不出意外,我可能只是无法排除与attr()jQuery 对象的方法相关的结果。提前致谢。

回答by prodigitalson

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

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

回答by Juraj Blahunka

it seems you have to use plain old vanilla javascript:

看来您必须使用普通的旧香草 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?

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

回答by womp

Could you get the DOM element from the jQuery wrapper using the get() function, and then iterate the DOM attributes?

您能否使用 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) {

        }
    }
}

For some much more robust DOM attribute handling, check this blog post.

对于一些更强大的 DOM 属性处理,请查看此博客文章

回答by Naeem Sarfraz

How about?

怎么样?

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

回答by Doug Neiner

While you can just use the standard DOM Element attribute attributes, it will include everyattribute (even those not explicitly set) in IE6. As an alternative, you can limit the number of attributes you set:

虽然您可以只使用标准的 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
    }
  })
});

回答by codepuppy

I am posting here because I think it may help others that arrive at this posting looking to parse an xml file as I was.

我在这里发帖是因为我认为它可能会帮助其他人看到这篇文章,希望像我一样解析 xml 文件。

I was looking for a method of traversing an xml file with a very similar structure to theracoonbear's fle and storing the results in an array and came across this posting.

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

I looked at prodigitalson's code but I simply could not get this syntax to work - with firefox complaining that in the line:

我查看了 prodigitalson 的代码,但我根本无法使用此语法 - Firefox 在行中抱怨:

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

that

this.attributes

this.属性

is not a defined function. I am quite sure that the error is entirely mine. But I have spent several hours attempting to get this working and have failed

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

What worked for me was (where my tag name is session instead of 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());
    });
});

I appreciate that this may not exactly answer the original question. However I hope that it may save other visitors to this post some time.

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

Regards

问候

回答by shmulik friedman

created this generic function that allows to look-in attributes as well as innearHtml:

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

回答by Kamil Kie?czewski

Pure JSFirst, your input xml is not valid, but you can fix it by close subitem tags by /

纯 JS首先,您输入的 xml无效,但您可以通过关闭 subitem 标签来修复它/

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