什么是递归树状菜单

三级联动这个功能很酷,里面运用到了递归函数,可以让数据呈树状排序,下面是我写的示例:



	
		
		
	
	
		
篮球明星NBA
   黑人
      科比
   白人
      库里
足球明星
   阿根廷
      梅西
   法国
      姆巴佩
兵乒球明星
   中国
      马龙
      刘国梁
      张继科

上面是基本样式,大家可以自己调一下;

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[i].name}
`; if(data[i].children.length > 0){ vray(data[i].children) } str += `
`; } } vray(newwData); document.getElementById('box').innerHTML = str; //for循环(data){ //str拼接; //if判断(data[i].children.length > 0){ //调用渲染函数vray(data[i].children); //} //str拼接结束标签
; //} //调用渲染函数;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里绑定,否则在其它地方获取不到他。

你可能感兴趣的:(java,前端,javascript)