事件委托实现树形菜单
HTML:
<ul class="tree" id="tree"> <li>Animals <ul> <li>Mammals <ul> <li>Cows</li> <li>Donkeys</li> <li>Dogs</li> <li>Tigers</li> </ul> </li> <li>Other <ul> <li>Snakes</li> <li>Birds</li> <li>Lizards</li> </ul> </li> </ul> </li> <li>Fishes <ul> <li>Aquarium <ul> <li>Guppy</li> <li>Angelfish</li> </ul> </li> <li>Sea <ul> <li>Sea trout</li> </ul> </li> </ul> </li> </ul>
JS:
<script> // 将所有li包装到span中 // 因为正常的li会占据100%的宽度,而span恰好是内容的宽度 //避免点击空白时触发事件 for (let li of tree.querySelectorAll('li')) { //创建span元素 let span = document.createElement('span'); //在每个li之前插入span li.prepend(span); //span的结尾插入span的下一个兄弟(是li) span.append(span.nextSibling); // move the text node into span } // catch clicks on whole tree tree.onclick = function(event) { if (event.target.tagName != 'SPAN') { return; } let childrenContainer = event.target.parentNode.querySelector('ul'); if (!childrenContainer) return; // no children childrenContainer.hidden = !childrenContainer.hidden; } </script>