[英]How to prevent other click events from running while one of them is already running in jQuery?
I am writing a simple fade-slideshow with previous
and next
buttons. 我正在使用
previous
和next
按钮编写一个简单的淡入淡出幻灯片。
The problem is that when I click the next
button very quickly (for example 2 times), before the first event finished, the second one will be executed, so for less than a second I will see, two images in my page. 问题在于,当我非常快地单击
next
按钮(例如2次)时,在第一个事件完成之前,将执行第二个按钮,因此我将在不到一秒钟的时间内看到页面中的两个图像。
$("#next_button").click(function (){
$("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
current_slide ++;
current_slide = current_slide % slides_number;
$("#slide"+current_slide).fadeIn(FADE_DURATION, function (){
$(".slide_image").not("#slide"+current_slide).attr("style", "display: none;");
});
});
});
In the last line, after fadeIn()
, I even tried to hide everything except current image, wishing the issue will be solved, but that doesn't work. 在最后一行中,在
fadeIn()
,我什至试图隐藏除当前图像以外的所有内容,希望问题会得到解决,但这是行不通的。
I read something about event.stopImmediatePropagation()
but I couldn't use it, or maybe it wasn't my solution. 我读了一些有关
event.stopImmediatePropagation()
但我无法使用它,或者这不是我的解决方案。
How to force jQuery
to ignore executing any similar events, before one of those same events, get finished? 在这些相同事件之一完成之前,如何强制
jQuery
忽略执行任何类似事件?
You can add a flag that indicates when your slider is in the middle of transitioning: 您可以添加一个标志,指示滑块何时处于过渡状态:
var isSliding = false;
$("#next_button").click(function (){
if(isSliding) {
return false;
}
isSliding = true;
$("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
current_slide ++;
current_slide = current_slide % slides_number;
$("#slide"+current_slide).fadeIn(FADE_DURATION, function (){
$(".slide_image").not("#slide"+current_slide).attr("style", "display: none;");
isSliding = false;
});
});
});
您可以绑定和解除绑定,但是如果重复很多次,这很费时间,如果您多次重复尝试,请尝试查看此答案: jQuery-在事件发生后如何临时禁用onclick事件监听器被解雇了?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.