0
<script>         
$(document).ready(function(){
            var xml = "<root> \
                        <method name='A'> \
                        <childcall name='B'></childcall> \
                        <childcall name='C'></childcall> \
                        </method> \
                        <method name='B'> \
                        <childcall name='D'></childcall> \
                        </method> \
                        <method name='C'> \
                        <childcall name='D'></childcall> \
                        <childcall name='E'></childcall> \
                        </method> \
                        </root>";

            var data = $.parseXML(xml);
            console.log(data);
            $(data).find('method').each(function(){
                var name = $(this).attr('name');
                $('<div class="items"></div>').html('<a href="'+name+'">'+name+'</a>').appendTo('#page-wrap');

            });
        });

     </script>
</head>
<body>
    <div id="page-wrap"></div>
</body>
</html>

此代码为父方法标签输出 ABC。所需的输出是 ABCBDCD E。如何递归遍历子节点以获得所需的输出?那会是深度优先搜索吗?

4

2 回答 2

1

试试这个:

// Loop through the parent items
$(data).find('method').each(function () {
    var name = $(this).attr('name');
    $('<div class="items"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap');

    // Loop through the child items
    $(this).find('childcall').each(function () {
        name = $(this).attr('name');
        $('<div class="items"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap');
    });
});
于 2013-04-09T12:18:53.277 回答
0

如果有人有兴趣构建所有嵌套节点,更新的代码如下

$(xml).find('thymeSiteMap').each(function () {
    var name = $(this).attr('en');
    var id= $(this).attr('id');
    console.log(id);
    $('<div class="items shift" id="'+id+'"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap');

    // Loop through the child items
    $(this).find('thymeNode').each(function () {
    	
    	var parent = $(this).parent().attr('id');
    	console.log("me "+$(this).attr('id') +" my parent "+parent);
        name = $(this).attr('en');
        var divname="div#"+parent+".items";
        console.log(divname);
        var id= $(this).attr('id');
    
        $('<div class="items shift" id="'+id+'"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo(divname);
    });
<!doctype html>
    <html >
      <head>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
       
       <style>
       
       .shift{
       	
       	position:relative;
       	left:20px;
       }
       
       
       </style>
      </head>
      <body>
        <div id="page-wrap" class="shift"></div>
 
      </body>
    </html>

于 2015-11-11T00:42:18.847 回答