javascript/jquery循环遍历div并使用click事件添加next/prev按钮

les*_*dru -1 javascript jquery for-loop

<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>
Run Code Online (Sandbox Code Playgroud)

我知道如何遍历div并获得每个div并不是什么大不了的事,但是我没有看到如何循环div并且只显示第一个的逻辑,然后onclick next显示第二个,依此类推(和以前一样).

无论是vanilla JS还是jQuery解决方案都可以作为解决方案,但我真正想要的是,如果有人能够解释它背后的确切逻辑,因为我无法真正看到它.

我可以发布一些我已经完成的代码,但这不是问题,而是如何编程逻辑

非常感谢

Bar*_*mar 6

使用:visible发现,因此目前正在显示的DIV,并.next().prev()去前进和后退.

$("#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();
});
Run Code Online (Sandbox Code Playgroud)
.step {
  display: none;
}
div.step:first-child {
  display: block;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)