Javascript for() loop in Drupal not working?
I've just spent a long time trying to figure out why my Javascript for() loop won't work in a Drupal block, I feel like I've checked out the syntax - any idea why this isn't working?!
$(document).ready(function() {
var i=0;
while (i<=5)
{
alert(i);
i++;
}
});
That doesn't do any开发者_如何学Pythonthing - and also if I put something like this in- does not work either:
for (var i=0; i<31; i++){
alert(i);
}
Thanks!
None of the alerts will happen until the thread is done executing. By that time, i has exceeded your limit. This is a very commonly asked question. You need to learn about closures in JavaScript.
Here's a good overview. There are also many answers to this question in StackOverflow.
http://james.padolsey.com/javascript/closures-in-javascript/
From that article, this code:
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = (function(n) {
return function() {
alert( 'You clicked on: ' + n );
};
})(i);
}
Which is similar to what you want.
精彩评论