闲来无事写了个三级树形菜单demo,基于Jquery,还有很多优化空间
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>三级树形菜单demo</title>
</head>
<body>
<ul>
<li>
<ul class="container_ul">
</ul>
</li>
</ul>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
// data和dataChild分别作为模拟的ajax数据
var data=[{
city:'北京0',
cityChild:['朝阳0','海淀0','东城区0']
},{
city:'北京1',
cityChild:['朝阳1','海淀1','东城区1']
},{
city:'北京2',
cityChild:['朝阳2','海淀2','东城区2']
},{
city:'北京3',
cityChild:['朝阳3','海淀3','东城区3']
},{
city:'北京4',
cityChild:['朝阳4','海淀4','东城区4']
}];
var dataChild=[{
country:'朝阳0',
countryChild:['朝阳子类0','朝阳子类1','朝阳子类2']
},{
country:'海淀0',
countryChild:['海淀子类0','海淀子类1','海淀子类2']
},{
country:'东城区0',
countryChild:['东城区子类0','东城区子类1','东城区子类2']
},{
country:'朝阳1',
countryChild:['朝阳子类1','朝阳子类2','朝阳子类3']
},{
country:'海淀1',
countryChild:['海淀子类1','海淀子类2','海淀子类3']
},{
country:'东城区1',
countryChild:['东城区子类1','东城区子类2','东城区子类3']
}]
var html='';
data.forEach(function(item,index){
console.log(index,'???');
html +='<li class="item'+index+'">'+item.city+'</li>';
})
$('.container_ul').append(html);
$('.container_ul').click(function(e){
e.stopPropagation();
console.log(e.target,'jjjjjj');
if(e.target.tagName.toUpperCase()=='LI'){
let a =e.target.className;
console.log(a,'aaaaa');
if(a.indexOf('last')>-1){
// 点击最后一级
return;
}
else if(a.indexOf('item_sec')>-1){
console.log('这是点击二级类的逻辑');
console.log($(e.target).find("ul"),'我是etarget');
console.log($(e.target).html());
var html2;
console.log($(e.target).find("ul").length,'??????????')
if($(e.target).find("ul").length>0){
$(e.target).children("ul").remove();
}else{
html2='<ul>';
dataChild.forEach(function(element, index) {
if(element.country==$(e.target).html()){
console.log(element.countryChild,index,'jhhhh');
element.countryChild.forEach(function(item, index) {
html2+='<li class="last">'+item+'</li>'
});
}
});
html2+='</ul>';
$('.'+a).siblings('.last').children().empty();
$('.'+a+' '+"ul").remove();
$(e.target).append(html2);
console.log(html2,'我是html22');
return;
}
}else{
let index=a.substr(a.length-1,1);
var html1="<ul>";
data[index].cityChild.forEach(function(item, index) {
html1 +='<li class="item item_sec">'+item+'</li>';// statements
});
html1+='</ul>';
console.log(e.target,'我是target');
console.log($(e.target).find('ul'));
if($(e.target).find('ul').length){
html1=''
}
$(e.target).siblings('.item').children().empty();
$('.'+a+' '+"ul").remove();
$(e.target).append(html1);
}
}
})
</script>
</body>
</html>