用jQuery迭代元素属性 [英] Iterating over element attributes with jQuery
问题描述
我知道可以使用 attr()
方法检索个别属性,但是我试图遍历所有属性的属性一个元素对于上下文,我在一些XML上使用jQuery ...
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...
例如
$(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'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.
推荐答案
最好的方法是直接使用节点对象使用 / code>属性。我的解决方案的唯一区别与其他人建议这种方法相比,我将使用
.each
而不是传统的js循环:
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 :-)
});
});
这篇关于用jQuery迭代元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!