如何使用 idref 解析 xml 元素
给定一些示例 data.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<data>
<categories>
<category id="google">
<name>Google</name>
</category>
<categories>
<display>
<categories>
<category idref="google"/>
</categories>
</display>
</data>
以及一些用于获取 data.xml
文件的 jquery 代码:
$.ajax( {
url: '/data.xml',
dataType: 'xml',
success: function( data )
{
$data = $( data );
// fetch categories to display
$categories = $data.find( 'display > categories > category' );
}
} );
什么是解析 category
的高效且紧凑的方法 $categories
中获取的元素通过其 idref
属性引用的 code> 元素?
我想出了如下的方法:
$categories.each( function() {
var $category = $data.find( 'categories > category[id=' + $( this ).attr( 'idref' ) + ']' );
} );
但我认为可能有一种更紧凑的方式来收集元素。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从
idref
属性创建 id 选择器:上面的代码使用 map() 和 $.unique() 构建一个包含所有引用
元素的唯一实例的数组。You can create id selectors from the
idref
attributes:The code above uses map() and $.unique() to build an array containing unique instances of all the referenced
<category>
elements.