[英]How to make click event work for toggleClass with stopPropagation?
I'm building a dropdown component. 我正在构建一个下拉组件。 I want to:
我想要:
I have the following code: 我有以下代码:
$('.js-dropdown-toggler').click(function(e){
$('.js-dropdown').removeClass('is-open');
$(this).next('.js-dropdown').toggleClass('is-open');
e.stopPropagation();
});
$('html').click(function(){
if ($('.js-dropdown').hasClass('is-open')) {
$('.js-dropdown').removeClass('is-open');
}
});
$('.js-dropdown').click(function(e){
e.stopPropagation();
});
It doesn't hide the dropdown on the second click on the same button. 第二次单击同一按钮时,它不会隐藏下拉菜单。 If to remove
$('.js-dropdown').removeClass('is-open');
如果要删除
$('.js-dropdown').removeClass('is-open');
then dropdowns remain when click on the another button. 然后单击另一个按钮时,下拉菜单仍然保留。
I guess the problem is with using click event for toggleClass with stopPropagation. 我猜问题出在对带有stopPropagation的toggleClass使用click事件。
I'll appreciate any help. 我将不胜感激。
Change your current code as shown below: 更改您的当前代码,如下所示:
$('.js-dropdown-toggler').click(function(e){
var current = $(this).next('.js-dropdown');
current.toggleClass('is-open');
$('.js-dropdown').not(current).removeClass('is-open');
e.stopPropagation();
});
$('html').click(function(){
if ($('.js-dropdown').hasClass('is-open')) {
$('.js-dropdown').removeClass('is-open');
}
});
The point is that your dropdowns should be "mutually exclusive": when one is showing up - the other goes to hide simultaneously. 关键是您的下拉菜单应该是“互斥的”:当一个出现时-另一个同时隐藏。
只需在处理程序中为'.js-dropdown-toggler'
删除此行:
$('.js-dropdown').removeClass('is-open');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.