如何使用按钮点击显示和显示div?

时间:2017-03-06 17:07:24

标签: javascript jquery

是否可以告诉我如何通过点击div按钮显示下一个next。点击div按钮时显示上一个previous

https://jsbin.com/zeleloxifo/edit?html,css,js,output

我有5 div。第一次first div显示。当用户点击next按钮时,它应显示second div并隐藏first div然后用户再次点击它隐藏second div并在third上一个when user click on div`上显示it show previous div .. ...

$(function(){

  $('#pre').click(function(){
    alert('pre');
    $('.imageBlock').hide();
     $('.imageBlock').show()
  })

  $('#next').click(function(){
    alert('next');
     $('.imageBlock').hide();
    $('.imageBlock').show()
  })

})

1 个答案:

答案 0 :(得分:2)

使用帮助计数器变量,该变量将保存实际显示图像的索引。然后,使用eq()函数显示当前索引的图像。

$(function() {

  var counter = 0;
  $('.currentPage').text(counter+1);
  $('#pre').prop('disabled', true);
  
  $('#next').click(function() {
    if (counter < 4) {
      counter++;
      $('.imageBlock').hide();
      $('.imageBlock').eq(counter).show();
    }
    $('.currentPage').text(counter+1);
  })
  $('#pre').click(function() {
    if (counter > 0) {
      counter--;
      $('.imageBlock').hide();
      $('.imageBlock').eq(counter).show();
    }
    $('.currentPage').text(counter+1);
  })
  
  $('#next, #pre').click(function() {
    if (counter == 0) {
      $('#pre').prop('disabled', true);
    } else if (counter == 4) {
      $('#next').prop('disabled', true);
    } else {
      $('#pre').prop('disabled', false);
      $('#next').prop('disabled', false);
    }
  })

})
div.imageBlock {
  width: 100px;
  height: 100px;
  border: 1px solid
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>

</head>

<body>
  <div class="slideno">
    <span class="currentPage">
    </span>/<span class="totalPage">5
    </span></div>
  <div class="imageBlock">1</div>
  <div class="imageBlock" style="display:none">2</div>
  <div class="imageBlock" style="display:none">3</div>
  <div class="imageBlock" style="display:none">4</div>
  <div class="imageBlock" style="display:none">5</div>
  <button id="next">next</button>
  <button id="pre">pre</button>
</body>

</html>