三级联动这个功能很酷,里面运用到了递归函数,可以让数据呈树状排序,下面是我写的示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="box"> <div> <span>篮球明星NBA</span> <div> <span> 黑人</span> <div> <span> 科比</span> <div></div> </div> <span> 白人</span> <div> <span> 库里</span> <div></div> </div> </div> </div> <div> <span>足球明星</span> <div> <span> 阿根廷</span> <div> <span> 梅西</span> <div></div> </div> </div> <div> <span> 法国</span> <div> <span> 姆巴佩</span> <div></div> </div> </div> </div> <div> <span>兵乒球明星</span> <div> <span> 中国</span> <div> <span> 马龙</span> <div></div> <span> 刘国梁</span> <div></div> <span> 张继科</span> <div></div> </div> </div> </div> </div> <script src="index.js"></script> </body> </html>
上面是基本样式,大家可以自己调一下;
let arr1 = [{ "name":"篮球明星NBA", "id":"1", "pid":"0" }, { "name":"黑人", "id":"2", "pid":"1" }, { "name":"白人", "id":"3", "pid":"1" }, { "name":"科比", "id":"4", "pid":"2" }, { "name":"库里", "id":"5", "pid":"3" }, { "name":"足球明星", "id":"6", "pid":"0" }, { "name":"阿根廷", "id":"7", "pid":"6" }, { "name":"法国", "id":"8", "pid":"6" }, { "name":"梅西", "id":"9", "pid":"7" }, { "name":"姆巴佩", "id":"10", "pid":"8" }, { "name":"兵乒球明星", "id":"11", "pid":"0" }, { "name":"中国", "id":"12", "pid":"11" }, { "name":"马龙", "id":"13", "pid":"12" }, { "name":"刘国梁", "id":"14", "pid":"12" }, { "name":"张继科", "id":"15", "pid":"12" } ] //创建一个函数 treeData(把data传过来、pid、空数组arr){ function treeData(data,pid,arr){ for(let i = 0;i<data.length;i++){ if(data[i].pid == pid){ arr.push(data[i]); } } for(let i = 0;i<arr.length;i++){ arr[i].children = treeData(data,arr[i].id,[]) } return arr; } //for循环(循环data){ //if判断(data数据传过来的pid是否等于当前数据pid 0){ //将符合条件的数据放到数组arr里; //} //} //for循环(循环数组arr){ //数组arr的下标i等于渲染函数treeData(data,数组arr的下标id、空数组[]); //} //返回数组arr; //} //声明一个全局变量newwData 让它的值等于treeData; let newwData = treeData(arr1,0,[]); //声明一个空字符串 str; let str = ''; //渲染函数 vray; //创建一个函数(data){ function vray(data){ for(let i = 0;i<data.length;i++){ str += `<div><span>${data[i].name}</span><div style="display:none;">`; if(data[i].children.length > 0){ vray(data[i].children) } str += `</div></div>`; } } vray(newwData); document.getElementById('box').innerHTML = str; //for循环(data){ //str拼接; //if判断(data[i].children.length > 0){ //调用渲染函数vray(data[i].children); //} //str拼接结束标签</div>; //} //调用渲染函数;vray(newData); //将box渲染到页面上; //} //事件委托addEventListener //box.addEventListener('click',function(e){ document.getElementById('box').addEventListener('click',function(e){ e = event || window.event; let self = e.srcElement || e.target; if(self.nextElementSibling.style.display =='none'){ self.nextElementSibling.style.display ='block'; }else{ self.nextElementSibling.style.display ='none'; } }); //做兼容(e = event || window.event); //声明一个全局变量 self 让它的值等于 e.sicElement || e.target; //if判断(self.nextElemrntSibling.style.display =='none'){ //self.nextElemrntSibling.style.display ='block'; //}else{ //self.nextElemrntSibling.style.display ='none'; //} //})
这是写在js里的执行操作,这里面运用到了事件委托!
它只能在js里绑定,否则在其它地方获取不到他。