2014-05-01 86 views
-2

我一直试图遍历每个部分中的一组列表项只有一次。也就是说,在滚动到特定的部分时,我想要一组列表项来迭代一次。这不应该重复持续滚动。jQuery - 在嵌套的每个循环中仅迭代一次

我写的代码遍历每个部分以及部分中的每个列表项,但它会在每个滚动条上继续。

我想这只遍历每个部分一次。

$(window).scroll(function(){ 
      var windscroll = $(window).scrollTop(); 
      $('body section').each(function(e){ 
      if($(this).position().top < windscroll){ 
       $(this).find(".inner-skills li").each(function(i){ 
       $(this).delay(i*500).animate({ 
       "width":"200px", 
       "opacity":1 
       },500); 

       }); 
      } 
      }) 
     }); 

回答

0

你需要unbind它:

$(window).scroll(function(){ 
    var windscroll = $(window).scrollTop(); 
    $('body section').each(function(e){ 
     if($(this).position().top < windscroll){ 
     $(this).find(".inner-skills li").each(function(i){ 
      $(this).delay(i*500).animate({ 
       "width":"200px", 
       "opacity":1 
      },500); 
     }); 
     } 
    }) 
    $(window).unbind('scroll'); 
}); 

编辑:

$(window).scroll(function(){ 
    var windscroll = $(window).scrollTop(); 
    $('body section').not('.completed').each(function(e){ //Loop through all sections WITHOUT class of completed 
     if($(this).position().top < windscroll){ 
     $(this).find(".inner-skills li").each(function(i){ 
      $(this).delay(i*500).animate({ 
       "width":"200px", 
       "opacity":1 
      },500); 
     }); 
     $(this).addClass('completed'); // add class of completed so it wont loop through this anymore 
     } 
    }) 
}); 
+0

这是行不通的。在解除绑定时,没有任何部分被迭代。我的代码的问题是,即使在完成动画时,滚动事件也会被触发,这将是不必要的计算。我只想遍历每个部分一次。每个部分都有一组列表项,这些列表项只能迭代一次! –

+0

了解现在,将编辑。 –

+0

根据您评论的新理解编辑答案。请现在尝试:) –

1

您可以使用一个变量来检查,如果你已经滚动或不

试试这个:

var already_scrolled = 0; 
$(window).scroll(function(){ 
     if(already_scrolled == 0){ 
     already_scrolled = 1; 
     var windscroll = $(window).scrollTop(); 
     $('body section').each(function(e){ 
      if($(this).position().top < windscroll){ 
       $(this).find(".inner-skills li").each(function(i){ 
       $(this).delay(i*500).animate({ 
        "width":"200px", 
        "opacity":1 
       },500); 

       }); 
      } 
     }) 
     } 
    }); 
+0

非常酷!我不知道.each()有一个内置的计数器。 –

+0

_I我希望这只能遍历每个部分只有一次._ - 这只会到达第一部分,不会遍历它们一次... –

+0

这样做会发生什么,我只能通过第一部分进行迭代!之后没有。 –