Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS添加后缀整数并从1旋转到4_Javascript_Jquery_Css - Fatal编程技术网

Javascript JS添加后缀整数并从1旋转到4

Javascript JS添加后缀整数并从1旋转到4,javascript,jquery,css,Javascript,Jquery,Css,我必须将class.background-1的后缀改为.background-2等,4之后返回1。像旋转木马一样 我的扳机是“咔嗒”,如下所示: $('.arrow-next').click(function () { // Here should be the code }); 这就够了 const $carousel = $('.carousel'); $('.arrow-next').click(function() { if ($carousel.classList

我必须将class
.background-1
的后缀改为
.background-2
等,4之后返回1。像旋转木马一样

我的扳机是“咔嗒”,如下所示:

$('.arrow-next').click(function () {
        // Here should be the code
});
这就够了

const $carousel = $('.carousel');
$('.arrow-next').click(function() {
  if ($carousel.classList.contains('background-1')) {
    $el.classList.remove('background-1');
    $el.classList.add('background-2');
  } else if ($carousel.classList.contains('background-2')) {
    $el.classList.remove('background-2');
    $el.classList.add('background-3');
  } else if ($carousel.classList.contains('background-3')) {
    $el.classList.remove('background-3');
    $el.classList.add('background-4');
  } else if ($carousel.classList.contains('background-4')) {
    $el.classList.remove('background-4');
    $el.classList.add('background-1');
  }
});
使用的动态解决方案

其思想是获取元素,获取完整的类名,并通过用下一个数字替换来动态增加该数字(使用模来确保它不会超过可用背景的最大数量)

Math.max
在增量到达
5
之后,以确保我们不会从
0
开始

const limit=5;
$('.arrow next')。单击(函数(){
常量ele=$(“.background”).get(0);
ele.className=ele
.类名
.替换(
/背景-([0-9])/g,
(u,p1)=>“背景-”+数学最大值((数字(p1)+1)%limit,1)
);
});
.background-1{
背景色:红色;
}
.背景-2{
背景颜色:蓝色;
}
.背景-3{
背景颜色:粉红色;
}
.背景-4{
背景颜色:绿色;
}
.背景{
高度:100px;
宽度:100px;
}

点击我

我将在
-
上拆分,将数字和模数解析为4,再加上1,最后重新合并。我尝试了currentSlide.removeClass('sample-1')和prevSlide.addClass('sample-2'),但我不知道如何旋转它或如何计算点击次数@AndreasHe有4个背景,这只适用于2个背景+这是真正的静态。。如果他突然有5到6个背景呢?“…我的触发点是点击”。:)这并不能完全回答这个问题,它不能处理超过4张幻灯片,而且这是一种糟糕的代码实践,因为它实际上是静态的