今天练习代码的时候遇到了一个小问题,在做栏目列表的伸缩显示的功能的时候,点击顶级的栏目无法将其二级的子栏目隐藏起来 (就是其子栏目的子栏目),教程的上使用的是利用ajax去查询点击栏目的所有子栏目 在逐一隐藏,自己想到了一个只用jQuery实现的方法
// 栏目伸缩
$('tr[pid != 0]').hide();
$('i#open').click(function(){
if ($(this).attr('class') == 'typcn typcn-plus') {
$(this).removeClass().addClass('typcn typcn-minus');
var id = $(this).parents('tr').attr('id');
$('tr[pid = '+id+']').show();
}else {
$(this).removeClass().addClass('typcn typcn-plus');
var id = $(this).parents('tr').attr('id');
var sonCate = $(this).parents('tr').nextAll('tr');
sonCate.each(function(k,v){
if ($(v).attr('pid') == 0) {
return false;
}
$(v).find('i#open').removeClass().addClass('typcn typcn-plus');
$(v).hide();
});
}
});
大致的思路就是获取点击栏目之后的所有非顶级栏目,循环隐藏,当遇到顶级栏目的时候跳出循环,即可达到相同的目的