<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>
此代码输出A B C作为父方法标记。所需的输出是A B C B D C D E. 如何递归遍历子节点以获得所需的输出?这会是深度优先搜索吗?
答案 0 :(得分: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');
});
});
答案 1 :(得分: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>