jQuery禁用多次点击

时间:2019-03-06 11:01:06

标签: javascript jquery

我正在尝试创建一个简单的JQuery滑块,并且在使用.on('click')函数时遇到了麻烦,如果我单击next或prev按钮的速度过快,则会超出我期望的值。

Jquery Simple Slider

var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;

$(".prev").on('click',function(){
if(currentSlide > 1){   
    $slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, function(){
        slideMarginLeft +=900;
            currentSlide--;
            console.log(currentSlide);
        });
}
});


$(".next").on('click',function(){
if(currentSlide < 5){   
    $slider.animate({marginLeft : slideMarginLeft} , slideSpeed, function(){
        slideMarginLeft -=900;
        currentSlide++;
        console.log(currentSlide);
    });
}
});

2 个答案:

答案 0 :(得分:2)

var currentSlide = 1;
var $slider = $(".slides");
var slideCount = $slider.children().length;
var slideSpeed = 500;
var slideMarginLeft = -900;
var slideMarginRight = 0;


function previousClickCallback(animationCallback){
    return function(){
        if(currentSlide > 1){   
            $slider.animate({marginLeft : slideMarginLeft + 1800} , slideSpeed, () => {
                slideMarginLeft +=900;
                currentSlide--;
                console.log(currentSlide);
                $(".prev").once('click',previousClickCallback);
            });
        } else {
          $(".prev").one('click',previousClickCallback);
        }
    }
}

function nextClickCallback(){
    return function(){
        if(currentSlide < 5){   
            $slider.animate({marginLeft : slideMarginLeft} , slideSpeed, () => {
                slideMarginLeft -=900;
                currentSlide++;
                console.log(currentSlide);
                $(".next").once('click',nextClickCallback);
            });
        } else {
         $(".next").one('click',nextClickCallback);
        }
        
    }
}


$(".prev").one('click',previousClickCallback);
$(".next").one('click',nextClickCallback)

这应该做,单击事件仅被注册一次,并且一旦完成动画的回调,则仅再次单击事件将被注册,这将从连续触发事件中停止

答案 1 :(得分:0)

确保.next类仅分配给一个按钮。