javascript - Toggling links in menu? -


how make links can works sub-items?

<ul>     <li><a href="item-1">item 1</a>         <ul>             <li><a href="item-1-1">item 1.1</a></li>         </ul>     </li>      <li><a href="item-2">item 2</a></li>      <li><a href="item-3">item 3</a>         <ul>             <li><a href="item-3-1">item 3.1</a>                 <ul>                     <li><a href="item-3-1-3">item 3.1.1</a></li> <li><a href="item-3-1-2">item 3.1.2</a></li>                 </ul>             </li>         </ul>     </li> </ul> 

i did basical example.

$('ul').on('click','a',function(){      if ($(this).next('ul').toggle()) return false;  }); 

this might toggling links sub-items , if link hasn't them go location in href, wont work, why?

ul li ul {     display:none; } 

actually, here fiddle: nested menu

it because .toggle() never return falsy value if called on non-existent elements. means if condition if ($(this).next('ul').toggle()) pass.

change to:

$('ul').on('click','a',function(){     if ($(this).next('ul').length > 0) {         $(this).next('ul').toggle();         return false;     } }); 

working demo


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -