【问题标题】:using .each on elements loaded after DOM在 DOM 之后加载的元素上使用 .each
【发布时间】:2014-09-23 07:03:24
【问题描述】:

我在选择由 JS 动态注入的一系列链接时遇到一些问题。基本上,一个 youtube 列表被构建并加载到 DOM 中。现在我想给它添加一点闪光(没有 CSS 动画,我的挑战,测试动态 jQuery 页面的限制真的很有趣)

但它只是不会选择在 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');
                }
            });         
        });

【问题讨论】:

    标签: jquery live each


    【解决方案1】:

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

    $(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');
    

    【讨论】:

    • 这是什么巫术!哈哈 非常感谢,我看了.on() 这么多次,没想到你不需要活动
    • @WASasquatch,那么希望你能接受答案:)
    • 是的,对不起,我等了 15 分钟,然后就睡着了。 :P
    【解决方案2】:

    您不必遍历每个元素来绑定事件。只需这样做

    $(".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');
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      相关资源
      最近更新 更多