带有glyphicon的JQuery .toggle()子菜单级别2不起作用

时间:2016-05-11 13:52:36

标签: jquery html twitter-bootstrap-3

所以我所拥有的是以下jquery代码:

$(document).ready(function(){
    $('.glyphicon.glyphicon-chevron-right.mainmenu').on('click', function() {
        $(this).toggleClass('opened');
        $(this).next('.submenu').toggle();
    });

    $('.glyphicon.glyphicon-chevron-right.submenu').on('click', function() {
        alert("hi");
        $(this).toggleClass('opened');
        $(this).next('.submenu').toggle();
    });
});

我的HTML结构如下所示:

<div class="glyphicon glyphicon-chevron-right mainmenu"></div>
<div class="submenu">
  <ul class="navbar-nav">
     <li><a>Plapla</a></li>
     <li><a>Plapla1</a></li>
     <li><a>Plapla2</a></li>
     <li><a>Plapla3</a></li>
     <li class="submenu">
       <a>Plapla4<7a>
       <div class="glyphicon glyphicon-chevron-right submenu"></div>
       <div class="submenu">
         <ul class="navbar-nav">
           <li><a>Plapla</a></li>
           <li><a>Plapla1</a></li>
         </ul>
       </div>
     </li>
   </ul>
</div>

所以单击glyphicon我试图打开下一个子菜单。这适用于第一个<div class="glyphicon glyphicon-chevron-right mainmenu"></div>但不适用于第二个<div class="glyphicon glyphicon-chevron-right submenu"></div>

我玩了一下但是找不到解决方案。代码似乎适合我。

1 个答案:

答案 0 :(得分:0)

我在代码中更改了一些内容。我想这就是你想要的。

$(document).ready(function() {
  $('.glyphicon.glyphicon-chevron-right.mainmenu').on('click', function() {
    $(this).toggleClass('opened');
    $(this).next('.submenu').toggle();
  });

  $('.glyphicon.glyphicon-chevron-right.submenu').on('click', function() {
    alert("hi");
    $(this).toggleClass('opened');
    $(this).next('.submenu').toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="glyphicon glyphicon-chevron-right mainmenu">
  Home
</div>
<div class="submenu">
  <ul class="navbar-nav">
    <li><a>Plapla</a>
    </li>
    <li><a>Plapla1</a>
    </li>
    <li><a>Plapla2</a>
    </li>
    <li><a>Plapla3</a>
    </li>
    <li class="submenu">
      <div class="glyphicon glyphicon-chevron-right submenu">
        <a>Plapla4</a>
      </div>
      <div class="submenu">
        <ul class="navbar-nav">
          <li><a>Plapla</a>
          </li>
          <li><a>Plapla1</a>
          </li>
        </ul>
      </div>
    </li>
  </ul>
</div>