JQuery children循环XML

时间:2015-04-25 18:22:11

标签: jquery xml children

使用JQuery和AJAX,我获取一个XML文档,然后循环遍历文档,尝试在XML标记/节点的每个级别执行某些操作,分别从父级到子级,然后是子级的子级。

我目前的作品是什么,但是专门针对儿童的孩子的限制(不理想)。

最终申请可能有一个开放式的子女数量来执行此操作。

How can i make this account for any number of children without the inefficiency?

我尝试过根据我希望在每个孩子级别实现的功能。但是这不能按预期工作,基本上打破了脚本。

功能

function childX() {
    $(this).children().each(function()
    {
       $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");
    });
}

主要脚本

  $(xml).find("RecentTutorials").children().each(function()
  {

    $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");


    $(this).children().each(function()
    {
       $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

      $(this).children().each(function()
        {
           $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

            $(this).children().each(function()
            {
               $("#output").append("<div id='"+(this).nodeName+"'>"+(this).nodeName+"</div><br />");

            });

        });

    });


  //alert((this).nodeName);
  }); 

1 个答案:

答案 0 :(得分:2)

最简单的方法可能是使用递归函数 - 即调用自身的函数。

addChildren( $(xml).find("RecentTutorials") );

function addChildren( $parent ) {
    $parent.children().each( function( i, child ) {
        $("#output").append(
            "<div id='" + child.nodeName + "'>" +
                child.nodeName +
            "</div><br />"
        );
        addChildren( $(child) );
    });
}

对于一个有趣的测试用例,尝试在任何使用jQuery的页面上打开JavaScript控制台 - 比如我们现在使用的那个 - 并粘贴在这个类似的代码中:

logChildren( $(document.body) );

function logChildren( $parent ) {
    $parent.children().each( function( i, child ) {
        console.log( child.nodeName );
        logChildren( $(child) );
    });
}

它将为页面中的每个元素打印nodeName

BTW我建议您在使用this时不要使用$(this)jQuery.each()。相反,请使用我的示例中的显式参数名称。以这种方式理解代码更容易,也更不容易出错。这是您的childX()功能根本不起作用的部分原因。它引用了第一行中的this,但是当您直接调用函数时,this不太可能符合您的预期:除非您使用严格模式,否则this是对window对象!