Domanda

I have classis HTML 2 level deep nav menu looking like this:

  <nav>
      <ul>
         <li><a href="#">1</a>
                <ul>
                     <li><a href="#">1.1</a><li>
                     <li><a href="#">1.2</a><li>
                     <li><a href="#">1.3</a><li>
                </ul>
          </li>

           <li><a href="#">2</a>
                <ul>
                     <li><a href="#">2.1</a><li>
                     <li><a href="#">2.2</a><li>
                     <li><a href="#">2.3</a><li>
                </ul>
          </li>

          <!-- etc -->

      </ul>
   </nav>

jQuery function should make it toggle on click. First level is fine, but down on the second level, when I hit anchor 1 , it doesn't open only the submenu related to that anchor element (1.1, 1.2, 1.3), but it toggles all the submenus (1.x, 2.x, 3.x, ..)at once. So how so I make it affect only the children of the anchor element that was clicked?

 jQuery(document).ready(function($){

  $('nav').prepend('<div id="menu-icon">Menu</div>');

  $("nav > ul").hide();

  $("nav > ul >li > ul").hide();

  $("#menu-icon").on("click", function(){
                       $("nav > ul").slideToggle();
                       $(this).toggleClass("active");
                           }
                     );


    $("nav > ul > li > a ").on("click", function(){
                                 $("nav > ul > li > ul").slideToggle();
                                 $(this).toggleClass("active");
                                     }
                             );




    });

UPDATE: Here is JSFiddle: http://jsfiddle.net/kNZ3E/

È stato utile?

Soluzione

without changing your code too much:

$("nav ul > li > a ").on("click", function(){
  $(this).siblings("ul").slideToggle();
   $(this).toggleClass("active");
 }
);

edit: You should be able to nest more lists using this code as well, considering it will always grab the sibling ul element if it exists. You may need to update your css however

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top