<script>
// 数组
const treeList = [{
title: '树形菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单',
children: [
{
title: '一级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
}
]
},
{
title: '二级菜单',
},
{
title: '三级菜单',
children: [
{
title: '一级小菜单'
},
{
title: '二级小菜单'
},
{
title: '三级小菜单'
}
]
},
]
},
{
title: '树形菜单2',
children: [
{
title: '树形展示'
}
]
}
]
// 遍历
function getTree(treeList) {
let html = '';
treeList.map(tree => {
html += `
<ul>
${
tree.children && tree.children.length ?
`
<li>
<div class="title clickable" onclick="toogle(this.parentNode.parentNode.lastElementChild)">${tree.title} </div>
</li>
<li class="hidden">
${getTree(tree.children)}
</li>
`
:
`
<li>
<div class="title">${tree.title} </div>
</li>
`
}
</ul>
`
})
return html
}
// 开关
function toogle(dom) {
console.log(dom);
if (dom.className.indexOf('hidden') !== -1) {
dom.classList.remove('hidden')
} else {
dom.classList.add('hidden')
}
}
document.getElementById('tree').innerHTML = getTree(treeList)
</script>
js原生动态展开折叠树形
最新推荐文章于 2023-09-19 09:43:27 发布