2015-12-10 56 views
2

我有一個簡單的菜單,我想這樣做,當你點擊菜單項打開一個嵌套列表。如果你雙擊然後它必須打開和關閉。如何使3個級別的下拉菜單?

HTML:

<ul class="menu"> 
    <li class="has-child">Click here 
     <ul> 
      <li class="has-child">Click here 
       <ul> 
        <li>Level 3</li> 
       </ul> 
      </li> 
      <li>Level 2</li> 
      <li>Level 2</li> 
     </ul> 
    </li> 
    <li>Level 1</li> 
    <li>Level 1</li> 
</ul> 

的jQuery:

$('li.has-child').on('click', function() { 
    var elem = $(this).children('ul'); 

    if (elem.is(':hidden')) { 
     elem.slideDown(500); 
    } else { 
     elem.slideUp(500); 
    } 
}); 

但是,當我在第二級點擊菜單項,那麼第一個被關閉。爲什麼會發生這種情況,以及如何解決它?

[JSFiddle]

回答

2

您需要停止從事件從父母傳播給孩子,反之亦然。您可以使用event.stopPropagation()

$('li.has-child').on('click', function (event) { 
    event.stopPropagation() 
    var elem = $(this).children('ul'); 
    if (elem.is(':hidden')) { 
     elem.slideDown(500); 
    } else { 
     elem.slideUp(500); 
    } 
}); 
+0

function()<< event is missed :) –

+0

完美,謝謝! –

+1

@ Mohamed-Yousef已添加, –

2

你需要使用stopPropagation

$(document).ready(function() { 
    $('li.has-child').on('click', function (event) { 

     event.stopPropagation(); 

     var elem = $(this).children('ul'); 
     if (elem.is(':hidden')) { 
      elem.slideDown(500); 
     } else { 
      elem.slideUp(500); 
     } 
    }); 
}); 

這則停止點擊冒泡到父li

Fiddle