使用jQuery .on()做一个下拉菜单 [英] Using jQuery .on() to make a drop-down menu
本文介绍了使用jQuery .on()做一个下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个jQuery下拉菜单,它增加了一个类,以确定它是否下降或上升。但是由于某种原因,.on()函数似乎没有响应点击。我做错了什么?
I'm trying to make a jQuery drop down menu, that adds a class to know if it's down or up. But for some reason the .on() function doesn't seem to respond to clicks. What are I doing wrong?
这是我的HTML:
<ul id="main-menu" class="menu">
<li>
<a href="http://example.com">Item 1</a>
</li>
<li class="drop-down">
<a href="http://example.com">Item 2</a>
<ul class="sub-menu">
<li>
<a href="http://example.com">Sub Item 1</a>
</li>
<li>
<a href="http://example.com">Sub Item 2</a>
</li>
<li>
<a href="http://example.com">Sub Item 3</a>
</li>
</ul>
</li>
<li>
<a href="http://example.com">Item 3</a>
</li>
</ul>
我的JS:
// Slide down
jQuery('#main-menu > li.drop-down > a').not('.active a').click(function(e){
e.preventDefault();
jQuery(this).closest('li.drop-down').addClass('active').find('ul.sub-menu').slideDown();
});
// Slide up
jQuery('#main-menu > li.drop-down.active > a').on('click', function(e){
e.preventDefault();
jQuery(this).closest('li.drop-down').find('ul.sub-menu').slideUp(400, function(){
jQuery(this).closest('li.drop-down.active').removeClass('active');
});
});
谢谢!
推荐答案
您不需要2个处理程序,您正在尝试实现。
You don't need 2 handlers for what you are trying to achieve.
您可以使用一个使用 toggleClass
和 slideToggle
jQuery方法。
You can just use one handler making use of toggleClass
and slideToggle
jQuery methods.
// Slide down
jQuery('#main-menu').on('click', 'li.drop-down > a', function(e){
e.preventDefault();
jQuery(this)
.closest('li.drop-down')
.toggleClass('active')
.find('ul.sub-menu')
.slideToggle(400, function(){
if($(this).is(':hidden')){
jQuery(this).closest('li.drop-down.active').removeClass('active');
}
});
});
参考文献: 。toggleClass(), .slideToggle()
References: .toggleClass(), .slideToggle()
这篇关于使用jQuery .on()做一个下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文