使用 jQuery 迭代元素属性

发布于 2024-08-20 21:16:32 字数 973 浏览 4 评论 0原文

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

I know individual attributes can be retrieved with the attr() method, but I'm trying to iterate over all of the attributes for an element. For context, I'm using jQuery on some 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>

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

っ左 2024-08-27 21:16:33

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

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

但我根本无法让这个语法工作 - 火狐在行中抱怨:

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

我查看了 prodigitalson 的代码,

this.属性

不是一个定义的函数。 我确信错误完全是我造成的。但我花了几个小时试图让它工作,但失败了

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

$(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 am posting here because I think it may help others that arrive at this posting looking to parse an xml file as I was.

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.

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

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

that

this.attributes

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

倾城花音 2024-08-27 21:16:33

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

created this generic function that allows to look-in attributes as well as 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); 
    }); 
}
看海 2024-08-27 21:16:33

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

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

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

孤寂小茶 2024-08-27 21:16:32

最好的方法是通过节点对象的 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 :-)
  });
});

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

$(xml).find('item').each(function() {
  $.each(this.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
     // do your magic :-)
  });
});
ㄟ。诗瑗 2024-08-27 21:16:32

看来你必须使用普通的旧香草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 元素中的所有属性?

it seems you have to use plain old vanilla 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?

浅笑轻吟梦一曲 2024-08-27 21:16:32

您能否使用 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 属性处理,查看此博文

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

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.

原野 2024-08-27 21:16:32

怎么样?

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

How about?

$(xml).find('item').each(function() {
  var attributes = $(this)[0].attributes;
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});
贩梦商人 2024-08-27 21:16:32

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

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

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
    }
  })
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文