我知道单个属性可以用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文档,和其他地方通过谷歌,但没有运气。如果没有别的,我可能只是有麻烦排除与jQuery对象的attr()方法相关的结果。提前致谢。
解决方法
最好的方法是通过使用其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 :-) }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。