如何在 html 中默认展开树视图

How to expand tree view by default in html

我一直在使用此处的树视图代码:https://www.w3schools.com/howto/howto_js_treeview.asp。当页面首次加载时,树完全折叠。我希望它得到充分扩展。有人可以帮助默认展开吗?

这是来自 w3schools.com 的 html 代码:


<ul id="myUL">
  <li><span class="caret">Beverages</span>
    <ul class="nested">
      <li>Water</li>
      <li>Coffee</li>
      <li><span class="caret">Tea</span>
        <ul class="nested">
          <li>Black Tea</li>
          <li>White Tea</li>
          <li><span class="caret">Green Tea</span>
            <ul class="nested">
              <li>Sencha</li>
              <li>Gyokuro</li>
              <li>Matcha</li>
              <li>Pi Lo Chun</li>
            </ul>
          </li>
        </ul>
      </li>  
    </ul>
  </li>
</ul>

这是来自 w3schools.com 的原始 javascript 脚本:

<script>
  var toggler = document.getElementsByClassName("caret");
  var i;

  for (i = 0; i < toggler.length; i++) {
    toggler[i].addEventListener("click", function() {
      this.parentElement.querySelector(".nested").classList.toggle("active");
      this.classList.toggle("caret-down");
    });
  }
</script>

只需添加一个 for 循环来切换 class,您将完全展开第一个视图。

<script>
  var toggler = document.getElementsByClassName("caret");
  var i;

  for (i = 0; i < toggler.length; i++) {
      toggler[i].parentElement.querySelector(".nested").classList.toggle("active");
      toggler[i].classList.toggle("caret-down");
}
  for (i = 0; i < toggler.length; i++) {
    toggler[i].addEventListener("click", function() {
      this.parentElement.querySelector(".nested").classList.toggle("active");
      this.classList.toggle("caret-down");
    });
  }
</script>