首页 > 解决方案 > 在按钮单击时循环遍历元素,然后全部隐藏,然后使用 jQuery 再次开始循环

问题描述

我试图通过单击按钮显示每个元素(我已经成功地做到了)来遍历一组元素。

我要做的下一部分是,在显示集合的最后一个元素之后,单击下一步按钮应该隐藏所有元素,然后单击下一步按钮应该从头开始循环。

更新:我想我快到了......它现在正在清除图像一旦它到达最后,但下一次点击已经跳转到第二个图像并跳过第一个。如何让它清除所有图像但仍然从头开始,“i = 0”?(codepen和下面的代码已经更新)

这是我的代码笔: https ://codepen.io/rrosegregoryy/pen/qBXVKVW

我的代码:

    $(document).ready(function () {
  //Elements to loop through
  var images = $(".click-image");
  //Start at 0
  i = 0;

  function showImage() {
    //Loop through elements
    $(images).each(function (index) {
      if (i == index) {
        //Show active element
        $(this).show();
      } else if (i == $(images).length) {
        //Show message
        $(this).show();
        //Reset if list number is reached
        $(images).hide();
        i = 0;
      }
    });

    i++;
  }

  //Run function on button click
  $(".and-button").click(showImage);
});
.and-button {
  position: absolute;
  font-size: 42px;
  top: 50%;
  left: 50%;
  cursor: pointer;
}

.click-image {
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
  display: none;
}

.is--1 {
  bottom: 25%;
  right: 10%;
}

.is--2 {
  top: 25%;
  left: 10%;
}

.is--3 {
  top: 15%;
  right: 30%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="click-image is--1"></div>
<div class="click-image is--2"></div>
<div class="click-image is--3"></div>
<div class="and-button">&</div>

标签: jquery

解决方案


你大概是这个意思?

我假设您一次只想显示一个。如果不是,请删除 .hide 语句

$(function() {
  //Elements to loop through
  const images = $(".click-image");
  //Start at 0
  let i = 0;
  const showImage = () => {
    if (i > $(images).length) {
      console.log("done"); // or reveal some other element
      i = 0;
      $(images).hide(); 
      // return; // comment this out to show the first image right away
    }
    $(images).eq(i).show()
    i++;
  };
  //Run function on button click
  $(".and-button").on("click", showImage);
});
.and-button {
  position: absolute;
  font-size: 42px;
  top: 50%;
  left: 50%;
  cursor: pointer;
}

.click-image {
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
  display: none;
}

.is--1 {
  bottom: 25%;
  right: 10%;
}

.is--2 {
  top: 25%;
  left: 10%;
}

.is--3 {
  top: 15%;
  right: 30%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="click-image is--1">img1</div>
<div class="click-image is--2">img2</div>
<div class="click-image is--3">img3</div>
<div class="and-button">&</div>


推荐阅读