gpt4 book ai didi

javascript - 循环遍历数组以记录单击时的元素时出现问题

转载 作者:行者123 更新时间:2023-12-03 07:35:18 25 4
gpt4 key购买 nike

您能否看一下这个演示,并让我知道如何在通过按钮点击触发时循环到 sectorArray[] 的不同元素并记录该元素?现在,我遇到一个问题:从减号或加号开始,并在函数到达最后一个元素时返回到开头!

var sectorArray = ["a", "b", "c"];
var counter = 0;
$(".plus").on("click", function(e) {
console.log(sectorArray[counter]);
counter++;
});
$(".minus").on("click", function(e) {
counter--;
console.log(sectorArray[counter]);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="minus">-</button>
<button type="button" class="plus" >+</button>

最佳答案

working fiddle

您需要做的就是在counter变量超出范围时重置它:

var sectorArray = ["a", "b", "c"];
var counter = -1; // start at -1 because we inc/dec before we log

$(".plus").on("click", function(e) {
// Increment and check if counter is out of bounds
if(++counter >= sectorArray.length){
counter = 0;
}
console.log(sectorArray[counter]);
});

$(".minus").on("click", function(e) {
// Decrement and check if counter is out of bounds
if(--counter < 0){
counter = sectorArray.length - 1;
}
console.log(sectorArray[counter]);
});

关于javascript - 循环遍历数组以记录单击时的元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com