2015-10-03 55 views

回答

2

這其實很簡單。它由一個遞歸節點列表組成。

您可以通過使用ullia同時實現的是:

<ul> 
    <li> 
    <a>Text here</a> 
    <!-- repeat --> 
    </li> 
</ul> 

並執行的行爲,這是很簡單的了。您必須查看a元素是否具有nextElementSibling,如果有,則是因爲當前節點有一個孩子。

看看下面的例子中,我創建:

(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); 
 
     } 
 
    } 
 
    }); 
 
})();
.hidden { 
 
    display: none; 
 
}
<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>