仅当存在嵌套子菜单时才切换类

时间:2019-04-13 08:00:03

标签: javascript

    <li class="treeview">
              <a href="#">
              </a>
    //nested submenu
              <ul class="treeview-menu">
                <li><a href="pages/layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li>
           </ul>
</li>

    <li class="treeview">
 //doesnt have submenu
              <a href="#">
              </a>
     </li>

我实现的方法无论如何都会添加菜单打开类。因此,我正在寻找一种仅在treeview-menu存在的情况下添加类的方法

var treeview = document.querySelectorAll(".treeview");
for (var i=0; i<treeview.length; i++) {
    treeview[i].addEventListener("click", function(e) {
    this.classList.toggle("menu-open");
    console.log(this);
});

3 个答案:

答案 0 :(得分:0)

下面的脚本获取单击的li.treeview元素的子级,将接收到的HTMLCollection对象转换为数组,然后对其进行过滤,以检查其中的一个是否具有.treeview-menu类。

<ul>
  <li class="treeview">
      <a href="#">test1</a>
    <!-- //nested submenu -->
    <ul class="treeview-menu">
      <li><a href="pages/layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li>
    </ul>
  </li>

  <li class="treeview">
  <!-- //doesnt have submenu -->
      <a href="#">test2</a>
  </li>
</ul>

<script>

var treeview = document.querySelectorAll(".treeview");
for (var i=0; i<treeview.length; i++) {
  treeview[i].addEventListener("click", function(e) {
    let childrenArray = [].slice.call(this.children),
        filteredChildrenArray = childrenArray.filter(function(element) {
          return element.className == "treeview-menu";
        });
    if (filteredChildrenArray.length > 0) {
      this.classList.toggle("menu-open");
      console.log("class changed.");
    }
  });
}

</script>

答案 1 :(得分:0)

如果我正确理解您的需求,则需要检查其中是否包含.treeview-menu。因此,您可以在每个querySelector元素上使用.treeview

var treeview = document.querySelectorAll(".treeview");
for (var i=0; i<treeview.length; i++) {
    const treeViewElement = treeview[i];
    if (treeViewElement.querySelector('.treeview-menu')) { // Checking for treeview-menu descendants
        treeviewElement.addEventListener("click", function(e) {
        this.classList.toggle("menu-open");
        console.log(this);
    }
});

(对委托也可以这样做,并保存一些侦听器。)

答案 2 :(得分:0)

您应该仅检查那些是treeview类的直接子级并且具有treeview-menu类的元素。我假设您只想在单击treeview类元素而不是treeview-menu类元素时切换类。

var treeview = document.querySelectorAll(".treeview > .treeview-menu");
console.log(treeview);
for (var i=0; i<treeview.length; i++) {
    treeview[i].parentNode.addEventListener("click", function(e) {
    this.classList.toggle("menu-open");
    console.log(this);
});
treeview[i].addEventListener("click", function(e) {
    e.stopPropagation();
    console.log(this);
});
}
<li class="treeview">
              <a href="#">
              </a>
    //nested submenu
              <ul class="treeview-menu">
                <li><a href="#"><i class="fa fa-circle-o"></i> Top Navigation</a></li>
           </ul>
</li>

    <li class="treeview">
 //doesnt have submenu
              <a href="#">
              </a>
     </li>