jquery - 在按钮单击时循环遍历元素,然后全部隐藏,然后使用 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>
解决方案
你大概是这个意思?
我假设您一次只想显示一个。如果不是,请删除 .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>
推荐阅读
- azure - Azure Cosmos DB -- 创建容器后更新冲突解决策略
- angular - 如何使用 nativescript 角度选项卡和 BottomNavigation 进行真正的延迟加载
- firebase - Firebase 模拟器没有突然进行身份验证
- python - Django HTML 遍历动态字典名称
- c# - 在 Godot 中,当我 GetNode 时,我访问的是运行时节点还是当前场景的节点?
- c# - 在循环中使用 C# 中的 ThreadPool 并等待所有线程完成
- javascript - 我正在使用 Mamp,所以我可以将 phpAdmin 用于我的 react native 项目。如何修复根文件夹
- git - git bisect 手动与 git bisect 运行
- python - ValueError:具有多个元素的数组的真值不明确。将 a.any() 或 a.all() 与 pymc3 一起使用
- json - 读取 S3 json 文件时出现 Pyspark 内存错误 - “java.lang.OutOfMemoryError:超出 GC 开销限制”