答案 0 :(得分:2)
您可以同时使用ul
,li
和a
来实现这一目标:
<ul>
<li>
<a>Text here</a>
<!-- repeat -->
</li>
</ul>
为了表现这种行为,它也非常简单。您必须查看a
元素是否有nextElementSibling
,如果有{1},则它是因为当前节点有子节点。
看一下我创建的下面的例子:
(function() {
var tree = document.getElementById('tree');
/* firstly, we hide all the child items */
[].forEach.call(tree.querySelectorAll('ul li a'), function(el, i) {
if (el.nextElementSibling)
el.nextElementSibling.classList.add('hidden');
});
/* here we make a event delegation, we add an event handler to the hole tree */
tree.addEventListener('click', function(e) {
var el = e.target;
/* if the element clicked is an anchor, it's because it's a node/leaf */
if (el.tagName === 'A') {
e.preventDefault();
/* if it has a nextElementSibling, it's because it has children, so it's a node */
if (el.nextElementSibling) {
/* we toggle the visibility of the child */
el.nextElementSibling.classList.toggle('hidden');
} else {
// do something with the final child (leaf)
console.log(el.textContent);
}
}
});
})();
&#13;
.hidden {
display: none;
}
&#13;
<div id="tree">
<ul>
<li>
<a>Father</a>
<ul>
<li>
<a>Son</a>
</li>
</ul>
</li>
<li>
<a>Grandfather</a>
<ul>
<li>
<a>Father</a>
<ul>
<li>
<a>Son</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a>Father</a>
<ul>
<li>
<a>Son</a>
</li>
</ul>
</li>
</ul>
</div>
&#13;