简体   繁体   中英

setTimeout in jQuery.each not working

I wanna imitate the menu item animation of this site

here's the key code I write to make the animation:

li{transition:transform 600ms}
li.animated{transform:translateY(20px)}

/* Javascript */
  $('nav ul li').each(function(i){
    setTimeout(function(){
      $('ul li').addClass('animated');
    },400*i)
  })

But it doesn't work, in this fiddle , the 4 items are being translated together, not "timeoutted" at all; strangely, in my actual site, the codes seem to be more broken, the class wasn't added at all. I inspected the code of my site and fiddle again, but I couldn't find where the problem is.

You can use the second parameter from the .each method to determine the element. Like:

$('.inOrder').click(function(){
  $('ul li').each(function(i, ele){
    setTimeout(function(){
      $(ele).addClass('animated');
    },400*i);
  })
})

https://jsfiddle.net/2pgf76vx/2/

You have to use this to target each elements individually,

  $('ul li').each(function(i){
    setTimeout(function(){
      $(this).addClass('animated');
    }.bind(this),400*i)
  });

DEMO

Or you can use arrow function to fix this,

  $('ul li').each(function(i){
    setTimeout(()=>{
      $(this).addClass('animated');
    },400*i)
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM