Jquery if 在 2 个数字之间

Jquery if between 2 numbers?

本文关键字:数字 之间 if Jquery      更新时间:2023-09-26

我正在使用以下Jquery尝试在某个幻灯片编号上添加类(使用Royalslider)。下面的代码适用于单个幻灯片编号,但您会注意到我也在尝试对一系列数字(例如,在幻灯片 5-9 之间)实现相同的效果。但是,这不起作用,并且仅对数组中的第一个数字触发。

任何帮助表示赞赏!

.JS

// Track slide number and add class
this.rsInstance().ev.on('rsAfterSlideChange', function() {
    if( this.currSlideId === 1) {
        $('.what').addClass('current');
    } 
    else {
        $('.what').removeClass('current');
    }
    if( this.currSlideId === 2) {
        $('.why').addClass('current');
    } 
    else {
        $('.why').removeClass('current');
    }
    if( this.currSlideId === ( 5 || 6 || 7 || 8 || 9 )) {
        $('.accolades').addClass('current');
    } 
    else {
        $('.accolades').removeClass('current');
    }
});

为什么不简单?

if (this.currSlideId >= 5 && this.currSlideId <= 9) {
    $('.accolades').addClass('current');
} else {
    $('.accolades').removeClass('current');
}

但是,如果要使用数组,请使用 indexOf() ,它返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回 -1。

if ([5,6,7,8,9].indexOf(this.currSlideId) > -1) {
    $('.accolades').addClass('current');
} else {
    $('.accolades').removeClass('current');
}

上述函数将在IE9+中工作,对于较旧的浏览器,您可以使用PolyFill或jQuery.inArray(value,array)

if (jQuery.inArray(this.currSlideId,[5,6,7,8,9]) > -1){
    $('.accolades').addClass('current');
} else {
    $('.accolades').removeClass('current');
}

您可以使用toggleClass()方法进一步改进代码

$('.accolades').toggleClass('current', this.currSlideId >= 5 && this.currSlideId <= 9);

完成

// Track slide number and add class
this.rsInstance().ev.on('rsAfterSlideChange', function() {
    $('.what').toggleClass('current', this.currSlideId === 1);
    $('.why').toggleClass('current', this.currSlideId);
    $('.accolades').toggleClass('current', this.currSlideId >= 5 && this.currSlideId <= 9);
});