jQuery:使用on('click')遍历数组 [英] JQuery: Iterate through an array by using on('click')
问题描述
我正在尝试进入JQuery,但仍在挣扎.
I am trying to get into JQuery but am struggling a bit around.
我想做的是一次单击一次数组,以便每次单击下一步"按钮时都会显示一个新项.
What I'm trying to do is go through an array one click at a time so that each time I click on the "next" button a new item is presented.
让我们看一下下面的代码:
Let's take a look at the following code:
$(document).ready(function(){
var stuff =["house","garden","sea","cat"];
for (var i=0; i<stuff.length;i++)
{
console.log(stuff[i]);
}
});
现在我在想什么,例如与我创建while循环
Now how I was thinking something like creating a while loop with i
$("#next").on('click', function(){i++;});
但是,这在某种程度上是行不通的. 任何人都可以以相对简单的方式向我解释如何做到这一点?
But this somehow doesn't work. Anyone able to explain to me how to do this in a relatively simple way?
推荐答案
使用for
语句遍历循环时,它会立即这样做,而不是响应事件.
When you run through your loop with the for
statement, it does so immediately and not in response to an event.
相反,您希望每次单击都逐步遍历数组.为此,您需要在点击功能之外定义一个计数器,并在每次点击时递增(或重置(如果已到达数组末尾)).
Instead, you want to step through the array with each click. To do so, you need to define a counter outside your click function and increment (or reset, if you've reached the end of the array) with each click.
以下是一些示例代码:
$(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
});
});
我希望这会有所帮助!
这篇关于jQuery:使用on('click')遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!