Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

jquery - Multiple counters in Javascript for loop

Before i tear my hair out and go down the wrong path in terms of debugging. Can someone confirm that this code will do as intended. Ie. animate 5 divs to different positions:

var i, j, k;
$('#menuButton').click(function(){
    for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){
        $('.spinner #item' + i).animate({
            left: '+=' + j,
            bottom: '+=' + k
          }, 500, function() {
            // Animation complete.
        });
    }
});

When i click the #menuButton, nothing happens and I get this error:

Uncaught SyntaxError: Unexpected token ; on the 'for()' line...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've got some semicolons where you want commas:

for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30) { /* do work */ }

You should only have three "statements" inside your for

for( [init]; [test]; [increments]) { [block] }

To do multiple [inits] or [increments] you have to use the sometimes magical, but oft forgotten, comma operator


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...