jquery使用Next / Prev按钮循环遍历多个div

时间:2016-12-03 01:14:47

标签: jquery html css

我正在使用以下代码循环完美无缺的div

$("#nextBtn").click(function() {
  var nextDiv = $(".step:visible").next(".step");
  if (nextDiv.length == 0) { // wrap around to beginning
    nextDiv = $(".step:first");
  }
  $(".step").hide();
  nextDiv.show();
});

$("#prevBtn").click(function() {
  var prevDiv = $(".step:visible").prev(".step");
  if (prevDiv.length == 0) { // wrap around to end
    prevDiv = $(".step:last");
  }
  $(".step").hide();
  prevDiv.show();
});
.step {
  display: none;
}
div.step:first-child {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
  <div class="step">This is step 1</div>
  <div class="step">This is step 2</div>
  <div class="step">This is step 3</div>
  <div class="step">This is step 4</div>

  <button id="prevBtn">Prev</button>
  <button id="nextBtn">Next</button>
</div>

我的问题是我会动态添加多组div和按钮,这会破坏下面的代码

$("#nextBtn").click(function() {
  var nextDiv = $(".step:visible").next(".step");
  if (nextDiv.length == 0) { // wrap around to beginning
    nextDiv = $(".step:first");
  }
  $(".step").hide();
  nextDiv.show();
});

$("#prevBtn").click(function() {
  var prevDiv = $(".step:visible").prev(".step");
  if (prevDiv.length == 0) { // wrap around to end
    prevDiv = $(".step:last");
  }
  $(".step").hide();
  prevDiv.show();
});
.step {
  display: none;
}
div.step:first-child {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="form">
  <div class="step">This is step 1</div>
  <div class="step">This is step 2</div>
  <div class="step">This is step 3</div>
  <div class="step">This is step 4</div>

  <button id="prevBtn">Prev</button>
  <button id="nextBtn">Next</button>
</div>
	
	
	<div class="form">
  <div class="step">This is step 5</div>
  <div class="step">This is step 6</div>
  <div class="step">This is step 7</div>
  <div class="step">This is step 8</div>

  <button id="prevBtn">Prev</button>
  <button id="nextBtn">Next</button>
</div>

我该如何使这项工作?因为我不能改变任何元素的类,也不知道会有多少元素?

0 个答案:

没有答案