开发者

Javascript for() loop in Drupal not working?

开发者 https://www.devze.com 2022-12-11 11:39 出处:网络
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?!

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号