javascript - JQuery: Iterate through an array by using on('click') -
i trying jquery struggling bit around.
what i'm trying go through array 1 click @ time each time click on "next" button new item presented.
let's take @ following code:
$(document).ready(function(){ var stuff =["house","garden","sea","cat"]; (var i=0; i<stuff.length;i++) { console.log(stuff[i]); } });
now how thinking creating while loop
$("#next").on('click', function(){i++;});
but somehow doesn't work. able explain me how in relatively simple way?
when run through loop for
statement, , not in response event.
instead, want step through array each click. so, need define counter outside click function , increment (or reset, if you've reached end of array) each click.
here sample code:
$(function () { // shortcut document ready var stuff = ['house', 'garden', 'sea', 'cat'], counter = 0; console.log(stuff[counter]); // initial value // next line, of course, assumes have element id="next" $('#next').click(function () { counter = (counter + 1) % stuff.length; // increment counter // modulus (%) operator resets counter 0 // when reaches length of array console.log(stuff[counter]); // new incremented value }); });
i hope helps!
Comments
Post a Comment