开发者

Basic understanding of loops in jQuery

I'm having a hard time understanding how to loop jQuery, I think my problem is I think in a PHP manner.

Lets say I've got this very simple example.

HTML:

<div style="background:#98bf21;height:100px;width:100px;position:relative">
开发者_运维技巧

JS

$(document).ready(function(){
$("div").animate({height:300},"slow");
$("div").animate({width:300},"slow");
$("div").animate({height:100},"slow");
$("div").animate({width:100},"slow");
});

Se it here

If i understood correctly, I would have to use .each() *

But I cant figure out how to make it work.

NOTE: This is only an example, I'm interested more in the approach you would take, rather the actual looping.

Thanks in advance, please ask if any clarification is needed!

*I'm not necessarily looking for an answer with .each(), any approach you take is fine for the learning purposes.


You just need a function you can kick off as the last animation's callback, like this:

$(function(){
    function loop() {
      $("div").animate({height:300},"slow")
              .animate({width:300 },"slow")
              .animate({height:100},"slow")
              .animate({width:100 },"slow", loop);
    }
    loop();
});

You can test it out here.


Stealing Nick's code so we can expand it to terminate after a number of iterations.

$(function(){
  function loop(n) {
    if(n > 0)
    {
      $("div").animate({height:300},"slow")
          .animate({width:300 },"slow")
          .animate({height:100},"slow")
          .animate({width:100},"slow")
          .animate({width:100 },"slow", loop(n-1));
    }
  }
  loop(5);
});

The second .animate({width:100},"slow" is not a typo. I don't understand why but the shrinking width animation doesn't occur without it.


jQuery (almost always) automatically applies the methods you run on every element returned by the selector.

In your example, every div on the page would be animated.

Also, jQuery is chainable, meaning you can remove a lot of duplicate code:

$(document).ready(function(){
$("div")
  .animate({height:300},"slow")
  .animate({width:300},"slow")
  .animate({height:100},"slow")
  .animate({width:100},"slow");
});

Also know that you can animate more than one property at a time with the .animate() method. Depending on your desired effect, you could combine the properties being animated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜