在DOM之后加载的元素上使用.each

问题描述:

我有一些问题选择由JS动态注入的一系列链接。基本上,YouTube列表已构建并加载到DOM中。现在我想添加更多的flare(没有CSS动画,我的挑战在这里,测试动态jQuery页面上的限制真的很有趣)在DOM之后加载的元素上使用.each

但是它只是不会选择在DOM之后加载的元素我尝试了大量的搜索解决方案无济于事。虽然我有一对熊,但到目前为止我已经过了1分钟的生日。耶,祝你生日快乐!

这里是我想,你可以看到在行动它(而失败)here

 $('.featured-video-link').each(function(){ // featured-video-links is added after DOM too 
      $(this).live({ 
       mouseenter: function() { 
        $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(62, 132, 210, 0.8)', 'color': 'rgba(255,255,255,1.0)' }, 'slow'); 
       }, 
       mouseleave: function() { 
        $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(0,0,0,0.5)', 'color': 'rgba(255,255,255,0.8)' }, 'slow'); 
       } 
      });   
     }); 

您可以使用下面的语法,你不需要循环,

$(document).on({ 
    mouseenter: function() { 
     $(this).find('.feat-vid-title').animate({ 
      'backgroundColor': 'rgba(62, 132, 210, 0.8)', 
      'color': 'rgba(255,255,255,1.0)' 
     }, 'slow'); 
    }, 
    mouseleave: function() { 
     $(this).find('.feat-vid-title').animate({ 
      'backgroundColor': 'rgba(0,0,0,0.5)', 
      'color': 'rgba(255,255,255,0.8)' 
     }, 'slow'); 
    } 
}, '.featured-video-link'); 
+1

这是什么巫术魔法!哈哈非常感谢,我看了'.on()'很多次,并没有意识到你没有__need__事件 – WASasquatch 2014-09-23 07:11:17

+0

@WASasquatch,那么希望你会接受答案:) – 2014-09-23 07:14:05

+1

对不起,我正在等待15分钟,然后睡着了。 :P – WASasquatch 2014-09-23 16:34:21

你不必遍历每个元素绑定事件。简单地做这样的

$(".featured-video-link").hover(
    function() { 
     $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(62, 132, 210, 0.8)', 'color': 'rgba(255,255,255,1.0)' }, 'slow'); 
    }, function() { 
     $(this).find('.feat-vid-title').animate({ 'backgroundColor': 'rgba(0,0,0,0.5)', 'color': 'rgba(255,255,255,0.8)' }, 'slow'); 
    } 
);