JQuery:使用on('click')迭代数组

JQuery: Iterate through an array by using on('click')

本文关键字:迭代 数组 click JQuery 使用 on      更新时间:2023-09-26

我正试图进入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
    });
});

我希望这对你有帮助!

只需在回调函数之外保留一个计数器,并在每次点击时增加它:

$(document).ready(function(){
    var i = 0;    
    var stuff =["house","garden","sea","cat"]; 
    $("#next").on('click' function(){
         i = (i+1)%stuff.length;
         console.log(stuff[i]);
    });
});
$(document).ready(function(){
   var currentPos = 0;
   $("#next").click(function()
   {
      currentPos++;
      printThings(currentPos);
   });
});
function printThings(maxLength)
{
   maxLength = maxLength > stuff.length ? stuff.length : maxLength;
   var stuff =["house","garden","sea","cat"];  
    for (var i=0; i<maxLength;i++)
    {
        console.log(stuff[i]);
    }  
}

我想在相反的方向上循环:

$("#prev").on('click', function(){
        stuff.reverse();
         i = (i+1)%stuff.length;
         console.log(stuff[i]);
    });

可以,但是会跳过一个值…

我将在表单中添加一个文本框。然后,在#next中单击function循环数组。在循环时将数组值与文本框中的值进行比较。获得匹配后,将文本框的值更改为循环中的下一个数组值,然后退出循环。