Jquery if 在 2 个数字之间
Jquery if between 2 numbers?
我正在使用以下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);
});
相关文章:
- 删除图形和数字之间的连字符(-)符号
- 计算HTML表TD中两个数字之间的百分比
- 通过变量在两个数字之间切换
- 如何创建一个确定2个数字之间值的函数
- 在 javascript 中,将数字之间出现的所有“-”替换为“:”
- Jquery if 在 2 个数字之间
- 如何在javascript中生成任意四个数字之间的随机数
- 验证javascript中的输入是否在2个数字之间
- 如何使除法符号在基本计算器的数字之间只出现一次
- 检查数字是否在两个数字之间
- 数字数组,检查当前值介于哪 2 个数字之间
- 字符串和数字之间的Javascript比较
- 我想创建一个从 50 到 1 的倒计时,但我不想在每个数字之间倒计时相同的时间量
- 如果数字在两个数字之间加/减 10 添加类
- Javascript - 求两个数字之间的距离
- 2 个数字之间的 Javascript 表单验证
- 如何使用javascript在两个数字之间随机决定
- 如何在谷歌地图上获取性别数字,并计算两个性别数字之间的距离
- 验证文本字段长度在2个数字之间
- 使用或不使用变量的数字之间的差异