[英]Having Issue on Looping Through an Array to Log elements on Click
您能否看一下这个演示,并让我知道当按钮单击触发时,如何循环到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>
您需要做的就是在超出范围时重置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]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.