通过从一个函数触发多个滑块返回setInterval冲突

时间:2013-07-30 17:58:41

标签: javascript jquery function slideshow setinterval

我正在尝试创建一个滑块功能,它会影响文档上的多个滑块元素。卡在setInverval值。

Here is testing jsFiddle.

Works perfect when its just one.

function repSlider(target) {
        target = $(target);
        targetEl = target.find('.drop_leds');
        targetEl.hide().first().addClass('active').show();
        totalEl = targetEl.length-1;

        setInterval(function() {
            curEl = target.find('.active.drop_leds').index();
            curEl == totalEl ? curEl = 0 : curEl += 1;
            console.log(curEl);//this gives bug
            targetEl.hide().removeClass('active')
            .eq(curEl).addClass('active').fadeIn(444);
        },3000);

}

repSlider('.targetClassA');
repSlider('.targetClassB');

也尝试了不同的方法,但结果是一样的。

$.fn.repSlider = function() {
        target = $(this);
        targetEl = target.find('.sliderEl');
        targetEl.hide().first().addClass('active').show();
        totalEl = targetEl.length-1;

        return window.setInterval(function() {
            curEl = target.find('.active.sliderEl').index();
            curEl == totalEl ? curEl = 0 : curEl += 1;
            console.log(curEl);//this gives bug
            targetEl.hide().removeClass('active')
            .eq(curEl).addClass('active').fadeIn(444);

    },3000);
}

$('.repSliderA').repSlider();
$('.repSliderB').repSlider();

1 个答案:

答案 0 :(得分:0)

解决了从函数中获取setInverval:

Here is working jsFiddle.

$('.targetClassA > div').hide().first().addClass('active').show();
$('.targetClassB > div').hide().first().addClass('active').show();
function repSlider(target) {
    target = $(target);
    targetEl = target.find('.drop_leds');
    totalEl = targetEl.length-1;

    curEl = target.find('.active.drop_leds').index();
    curEl == totalEl ? curEl = 0 : curEl += 1;
    console.log(curEl);//this gives bug
    targetEl.hide().removeClass('active')
    .eq(curEl).addClass('active').fadeIn(444);

}

var repSliderAInt = setInterval(function() {
    repSlider('.targetClassA');
},3000);
var repSliderBInt = setInterval(function() {
    repSlider('.targetClassB');
},3000);