在$(document).ready函数内停止JQuery函数

时间:2021-08-10 15:59:31

I have a JQuery slider that starts automatically whenever the page loads. I also have next (nextSlide function) and previous (prevSlide function) buttons that work. What i'm trying to accomplish is this... I would like to STOP the 'autoSwitch' whenever the $('#next').on('click',nextSlide); or $('#prev').on('click',prevSlide); is activated.

我有一个JQuery滑块,只要页面加载就会自动启动。我还有next(nextSlide函数)和previous(prevSlide函数)按钮。我想要完成的是......我想在$('#next')。on('click',nextSlide)时停止'autoSwitch';或$('#prev')。on('click',prevSlide);被激活了。

In other words, autoswitch works on page load but stops as soon as user clicks the 'next' or 'previous' button.

换句话说,自动切换适用于页面加载,但只要用户单击“下一个”或“上一个”按钮就会停止。

$(document).ready(function() {
var autoSwitch = true;          // auto slider
var autoswitch_speed = 4000;    // auto slider speed

// Add initial active class
$('.slide').first().addClass('active');

// Hide slides
$('.slide').hide();

// Show first slide
$('.active').show();

// Next handler
$('#next').on('click',nextSlide);

// Previous handler
$('#prev').on('click',prevSlide);

// AutoSwitch handler
if (autoSwitch == true) {
    setInterval(nextSlide,autoswitch_speed);
}

// Switch to next slide
function nextSlide () {
    $('.active').removeClass('active').addClass('oldActive');
    if ($('.oldActive').is(':last-child')) {
        $('.slide').first().addClass('active');
    } else {
        $('.oldActive').next().addClass('active');
    }
    $('.oldActive').removeClass('oldActive');
    $('.slide').fadeOut(speed);
    $('.active').fadeIn(speed);
}

// Switch to prev slide
function prevSlide () {
    $('.active').removeClass('active').addClass('oldActive');
    if ($('.oldActive').is(':first-child')) {
        $('.slide').last().addClass('active');
    } else {
        $('.oldActive').prev().addClass('active');
    }
    $('.oldActive').removeClass('oldActive');
    $('.slide').fadeOut(speed);
    $('.active').fadeIn(speed);
}
});

1 个解决方案

#1


2  

When you run setInterval store a reference to it:

当您运行setInterval存储对它的引用时:

var intervalID = setInterval(nextSlide,autoswitch_speed);

Then when your direction buttons are hit clear that interval:

然后当你的方向按钮被击中时,清除该间隔:

$('#next, #prev').on('click', function(){
    clearInterval(intervalID);
});

(Note: This onclick handler must be within your $(document).ready function to have scope of the intervalID variable)

(注意:此onclick处理程序必须在$(document).ready函数内,以具有intervalID变量的作用域)

#1


2  

When you run setInterval store a reference to it:

当您运行setInterval存储对它的引用时:

var intervalID = setInterval(nextSlide,autoswitch_speed);

Then when your direction buttons are hit clear that interval:

然后当你的方向按钮被击中时,清除该间隔:

$('#next, #prev').on('click', function(){
    clearInterval(intervalID);
});

(Note: This onclick handler must be within your $(document).ready function to have scope of the intervalID variable)

(注意:此onclick处理程序必须在$(document).ready函数内,以具有intervalID变量的作用域)