全局if条件到本地if条件

时间:2015-04-27 09:51:05

标签: jquery

下面是一个用于计算幻灯片编号的脚本,如1,2,3,4等

$(document).ready(function(){
    var slidesLength = $('#main-work-slider .carousel-inner .item').length,
    replaceSlidesLength = $('.slides-counter .slides-length').html('/ ' + slidesLength),
    addSlides = 1,
    slideNumber = $('.slides-number'),
    ourWorkNext = $('.our-work-controls .right'),
    ourWorkPrev = $('.our-work-controls .left');
    ourWorkNext.click(function(){
        slideNumber.html((addSlides += 1));

        /* here the if condition which is working fine with next button but
           it effects also on the prev button (global if condition) when i reach
           the boundry and go prev it gives me '-1' because the if condition has
           a global closure and i want to know how can i make it local to its
           function */

        if(addSlides >= slidesLength){

            addSlides = 0;
        }
    });

    ourWorkPrev.click(function(){
        slideNumber.html((addSlides -= 1));
    });
});

1 个答案:

答案 0 :(得分:0)

您应该在设置之前检查addSlides的值,如果值低于零,则相应地将其设置为幻灯片的长度。

ourWorkPrev.click(function(){
    addSlides -= 1;
    if(addSlides<0)addSlides = slidesLength;
    slideNumber.html(addSlides);
});