我正在尝试学习 JQuery,但有点挣扎。
我正在尝试做的是一次单击一个数组,以便每次单击“下一步”按钮时都会显示一个新项目。
我们来看下面的代码:
$(document).ready(function(){
var stuff =["house","garden","sea","cat"];
for (var i=0; i<stuff.length;i++)
{
console.log(stuff[i]);
}
});
现在我是怎么想的,比如用 i 创建一个 while 循环
$("#next").on('click', function(){i++;});
但这在某种程度上不起作用。 谁能以相对简单的方式向我解释如何做到这一点?
最佳答案
当您使用 for
语句运行循环时,它会立即执行,而不是响应事件。
相反,您希望每次单击都遍历数组。为此,您需要在点击函数之外定义一个计数器,并在每次点击时递增(或重置,如果您已到达数组末尾)。
下面是一些示例代码:
$(function () { // this is a shortcut for document ready
var stuff = ['house', 'garden', 'sea', 'cat'],
counter = 0;
console.log(stuff[counter]); // your initial value
// the next line, of course, assumes you have an element with id="next"
$('#next').click(function () {
counter = (counter + 1) % stuff.length; // increment your counter
// the modulus (%) operator resets the counter to 0
// when it reaches the length of the array
console.log(stuff[counter]); // the new incremented value
});
});
希望对您有所帮助!
关于javascript - JQuery:使用 ('click' 遍历数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549183/