<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');
$(this).children('childcall').each(function(){
name = $(this).attr('name');
$('<div class="items"></div>').html('<a href="'+name+'">'+name+'</a>').appendTo('#page-wrap');
});
});
});
</script>
<body>
<div id="page-wrap"></div>
</body>
以上代码遍历 xml 并将项目打印为 - A B C B D C D E。 我想让它成为一个可折叠的列表,就像在给定的链接中一样:http://www.sendesignz.com/index.php/jquery/77-how-to-create-expand-and-collapse-list-item-using-jquery
关于如何使其可折叠的任何提示?
编辑:感谢您的帮助。抱歉,我不能接受不止一个答案是正确的。所以式流解也是正确的。
最佳答案
首先,您需要生成与该示例相同的 HTML(使用 ul 和 li 而不是 div)
$(data).find('method').each(function(){
var hasChild = $(this).children('childcall').length > 0;
curLi += '<li';
curLi += ((hasChild) ? ' class="category plusimageapply">': '>');
curLi += $(this).attr('name');
if(hasChild){
curLi += '<ul>';
$(this).children('childcall').each(function(){
var name = $(this).attr('name');
curLi += '<li><a href="'+name+'">'+name+'</a></li>';
});
curLi += '</ul>';
}
curLi += '</li>';
});
$('#test').append(curLi);
请注意,它可以被优化。
然后,你需要指明一些CSS(隐藏 child ,添加+和-等)
.category ul{display:none;}
最后,你需要应用他们的JS
$('li.category').click(function(event){
if($(this).is('.plusimageapply')) {
$(this).children().show();
$(this).removeClass('plusimageapply');
$(this).addClass('minusimageapply');
}
else
{
$(this).children().hide();
$(this).removeClass('minusimageapply');
$(this).addClass('plusimageapply');
}
});
关于javascript - 使用 JQuery 的可折叠列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922108/