jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用jQuery从XML中查找后代大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 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,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()只给我节点的直接子节点.它不会给它的孙子孙女.例如,对于测试,它将仅警告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);
});

JsFiddle

作为一个单独的功能

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

JsFiddle

希望能帮助到你!

大佬总结

以上是大佬教程为你收集整理的使用jQuery从XML中查找后代全部内容,希望文章能够帮你解决使用jQuery从XML中查找后代所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: