我有一个 XML 文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<childrens>
<child id="1" value="Root Catalog" parent_id="0">
<child id="2" value="Apparel" parent_id="1">
<child id="3" value="Accessories" parent_id="2">
<child id="4" value="Handbags" parent_id="3">
<child id="5" value="Jewelry" parent_id="4"/>
<child id="6" value="test1" parent_id="4"/>
<child id="7" value="test2" parent_id="4"/>
<child id="15" value="test3" parent_id="4"/>
</child>
</child>
</child>
<child id="8" value="test_A" parent_id="1">
<child id="9" value="test_B" parent_id="8">
<child id="10" value="test_C" parent_id="9">
<child id="11" value="test_D" parent_id="10"/>
</child>
</child>
</child>
.
.
.
.
.
.
<child id="1111" value="test" parent_id="1">
<child id="1112" value="test1" parent_id="1111">
<child id="1113" value="test12" parent_id="1112">
<child id="1114" value="test123" parent_id="1113"/>
<child id="1115" value="test1234" parent_id="1114"/>
</child>
</child>
<child id="1116" value="test12345" parent_id="1111"/>
</child>
</child>
</childrens>
我想找到特定节点的所有后代(所有子节点直到叶节点)。例如,此处 test
的后代是 test1,test12,test123,test1234 & test12345
如果我找到 test1
的后代,则结果将为 test12,test123,test1234
。
$(document).ready(function(){
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('child[value="test"]').children().each(function(){
var i = $(this).attr('value');
alert(i);
});
}
});
});
使用 jQuery .children()
只给我该节点的直接子节点。它不会给它的孙子。例如,对于 test
,它只会提醒 test1 & test12345
。
最佳答案
可以通过先序遍历来实现。它是一个递归函数,女巫将按照您想要的顺序处理节点。参见 How to write a simple preorder DOM tree traversal algorithm in jQuery?
考虑@k-prime 的回答,你的例子将是:
$(xml).find('child[value="test"]').children().each (function processNodes()
{
alert($(this).attr('value'));
if (this.nodeType != 3)
$(this).children().each(processNodes);
});
作为一个单独的函数:
function recursiveDescendantsValues(node, arr) {
node.children().each(function () {
arr.push($(this).attr('value'));
if ($(this).nodeType != 3) {
recursiveDescendantsValues($(this), arr);
}
});
}
jQuery.fn.descendantsValues = function() {
var arr = []
recursiveDescendantsValues($(this), arr);
return arr;
};
希望对您有所帮助!
关于jquery - 使用 jQuery 从 XML 中查找后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14660710/