我正在尝试制作一个简单的进度栏,其中click事件会根据我的CSS类更改类:

所以我需要做的是确定当前类是什么,并更改类的最后一个字符,以便当前条形为:

用户单击下一步按钮:

该脚本将是?



$(document).on('click', '.progress-next', function() {
  //1. get current step-?
  //2. incriment current step + 1
  //3. remove current step-? from .progress-bar (once i know how to handle getting the classes i have this part :)
  //4. add new incremented class to .progress-bar (once i know how to handle getting the classes i have this part :)
});

.progress-bar {
  &.step-1 {
    width: 25%;
  }
  &.step-2 {
    width: 50%;
  }
  &.step-3 {
    width: 75%;
  }
  &.step-4 {
    width: 100%;
  }
}

<div class="progress">
	<div class="progress-bar progress-bar-striped step-1 active">Start</div>
</div>
<button class="btn btn-default progress-next">Next</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

最佳答案

试试这个,它应该是您想要的。

我离开了您的步骤,以便您可以遵循代码及其作用。



$(document).on('click', '.progress-next', function() {
  //1. get current step-?

  var cl = $(".progress-bar").attr("class").split(/\s/).filter(function( cn ) {
        return cn.indexOf('step') === 0;
    });
  //console.log(cl)

  //2. incriment current step + 1
  var step = parseInt(cl[0].split('-')[1]) + 1;
  //console.log(step)

  //3. remove current step-? from .progress-bar (once i know how to handle getting the classes i have this part :)
  var newclass = "step-" + step;
  //console.log(newclass)

  //4. add new incremented class to .progress-bar (once i know how to handle getting the classes i have this part :)
  $(".progress-bar").removeClass(cl[0]).addClass(newclass)

})

.progress-bar {
  background-color: blue;
}

.progress-bar.step-1 {
  width: 25%;
}

.progress-bar.step-2 {
  width: 50%;
}

.progress-bar.step-3 {
  width: 75%;
}

.progress-bar.step-4 {
  width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
  <div class="progress-bar progress-bar-striped step-1 active">Start</div>
</div>

<button class="btn btn-default progress-next">Next</button>

关于javascript - jQuery/JS进度条在单击按钮时更改类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45297198/

10-12 13:39