多个下一个/上一个在同一页面上

时间:2017-07-07 14:08:23

标签: jquery

我有一个包含许多部分的div。 我设法隐藏除第一个之外的所有部分,并添加下一个/上一个按钮。

如果单击“下一步”按钮,则会隐藏第一个按钮并显示第二个部分,依此类推。如果单击“上一个”,它将以相同的方式返回。

问题是,如果我的页面中有几个这样的div,则一个按钮可以显示/隐藏所有div而不仅仅是它自己的div。

我的计数器搞砸了,因为它计算页面中的所有部分而不是分别在每个div中。

$(function() {

  /* add next/previous buttons to all class body_next */
  $(".body_next").append('<button type="button" class="next">Next &#62;</button>');
  $(".body_next").append('<button type="button" class="prev" style="display:none">&#60; Previous</button>');

  var tracker = 1;
  var n = $(".section_next").length;

  /* hide all section_next except the first */
  $(".body_next").each(function() {
    $(".section_next:not(:first)", this).hide();
  });

  $(".next").click(function() {
    $(".section_next:visible").next(".section_next:hidden").show().prev(".section_next:visible").hide();

    tracker++;

    /* show previous button if displayed section is not the first one */
    if (tracker > 1) {
      $(".prev").show();
    }

    /* hide next button if displayed section is the last one */
    if (tracker == n) {
      $(".next").hide();
    }
  });

  $(".prev").click(function() {
    $(".section_next:visible").prev(".section_next:hidden").show().next(".section_next:visible").hide();

    tracker = tracker - 1;

    /* show next button if displayed section is not the first one */
    if (tracker > 1) {
      $(".next").show();
    }

    /* hide previous button if displayed section is the first one */
    if (tracker == 1) {
      $(".prev").hide();
    }
  });
});
p {
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="body_next">
  <section class="section_next">
    <p>blah1</p>
    <p>blah1</p>
    <p>blah1</p>
  </section>
  <section class="section_next">
    <p>blah2</p>
    <p>blah2</p>
    <p>blah2</p>
  </section>
</div>
<div class="body_next">
  <section class="section_next">
    <p>blah1</p>
    <p>blah1</p>
    <p>blah1</p>
  </section>
  <section class="section_next">
    <p>blah2</p>
    <p>blah2</p>
    <p>blah2</p>
  </section>
  <section class="section_next">
    <p>blah3</p>
    <p>blah3</p>
    <p>blah3</p>
  </section>
</div>

1 个答案:

答案 0 :(得分:0)

检查solution demo

Version 2将按钮置于禁用状态而不是隐藏。

您应该在父.section_next元素中找到.prev .next .body_next元素等元素。

相关问题