jQuery List切换孩子

时间:2015-05-13 19:05:57

标签: javascript jquery html

我的问题是,当我点击#topmenu时,它与另一个菜单

发生冲突

我想在点击li时打开子元素

Javascript代码:

$("#topmenu").click(function(){
  $(".treeview-menu").addClass("treeview-menu open").toggle();
});

HTML

<ul class="sidebar-menu" id="treeview-menu">
  <li class="treeview" id="topmenu">
    <a href="#"><i class="fa fa-table"></i><span>Financeiro</span>
      <i class="fa fa-angle-left pull-right"></i></a>
    <ul class="treeview-menu">
      <li><a href="#"><i class="fa fa-circle-o"></i>Pagamentos</a></li>
        <li><a href="#"><i class="fa fa-circle-o"></i>Relatórios</a></li>
    </ul>
  </li>
  <li class="treeview" id="topmenu">
    <a href="#"><i class="fa fa-table"></i><span>Financeiro</span>
     <i class="fa fa-angle-left pull-right"></i></a>
    <ul class="treeview-menu">
      <li><a href="#"><i class="fa fa-circle-o"></i>Pagamentos</a></li>
      <li><a href="#"><i class="fa fa-circle-o"></i>Relatórios</a></li>
    </ul>
  </li>
</ul>

2 个答案:

答案 0 :(得分:0)

更改了第2个ul和li标签的类名和ID名称。工作正常

   <!DOCTYPE html>
    <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
      <style>

      </style>
    </head>
    <body>
      <ul class="sidebar-menu" id="treeview-menu">
           <li class="treeview" id="topmenu">
                 <a href="#"><i class="fa fa-table"></i><span>Financeiro</span>
                 <i class="fa fa-angle-left pull-right"></i></a>
                 <ul class="treeview-menu">
                    <li><a href="#"><i class="fa fa-circle-o"></i>Pagamentos</a></li>
                    <li><a href="#"><i class="fa fa-circle-o"></i>Relatórios</a></li>
                 </ul>
              </li>
              <li class="treeview1" id="topmenu1">
                 <a href="#"><i class="fa fa-table"></i><span>Financeiro</span>
                 <i class="fa fa-angle-left pull-right"></i></a>
                 <ul class="treeview-menu1">
                    <li><a href="#"><i class="fa fa-circle-o"></i>Pagamentos</a></li>
                    <li><a href="#"><i class="fa fa-circle-o"></i>Relatórios</a></li>
                 </ul>
              </li>
      </ul>

    <script>
    $(document).ready(function(){

      $(document).ready(function(){

  $("#topmenu").click(function(){
      $(".treeview-menu").addClass("treeview-menu open").toggle();
  });

  $("#topmenu1").click(function(){
      $(".treeview-menu1").addClass("treeview-menu open1").toggle();
  });
     }); 

    </script>

    </body>
    </html>

答案 1 :(得分:0)

你有同名的ID混合。

使用类来解决常见的JS行为。

$(".treeview").click(function(){
    $(this).find(".treeview-menu").addClass("open").toggle();
});