【问题标题】:jquery hover, mouseenter, and mouseleave not working after .appendTojquery hover、mouseenter 和 mouseleave 在 .appendTo 之后不起作用
【发布时间】:2014-03-18 04:17:08
【问题描述】:

我在 $document.ready() 中绑定 mouseenter 和 mouseleave 事件,如下所示:

$( ".collection_add_to" ).hover(
    function() { $(this).find( ".playlists" ).fadeIn("fast"); },
    function() { $(this).find( ".playlists" ).fadeOut("fast"); }
);

用户可以请求更多具有“.collection_add_to”类的搜索结果。它们被附加到现有的搜索结果中,如下所示:

$.get("context/collection/", $data, function(result) {
    $( result ).appendTo( "#collection_song_items" );
    // rebind_hover();
});

我仔细检查了返回的结果是否具有“.collection_add_to”类。我还尝试在额外的例程中重新绑定它:

function rebind_hover() {
    $( ".collection_add_to" ).hover(
        function() { $(this).find( ".playlists" ).fadeIn("fast"); },
        function() { $(this).find( ".playlists" ).fadeOut("fast"); }
    );
}

没有任何效果,悬停事件不再适用于新添加的项目。使用 $load() 函数时,它可以工作。如何使悬停事件在动态加载的内容上再次起作用,尤其是在使用 append() 或 appendTo() 添加内容时?

编辑

感谢 irc 上的 sacho 和 Raminson:

$(document).on("mouseenter", ".collection_add_to", function() {
           console.log("MOUSEENTER");
});
$(document).on("mouseleave", ".collection_add_to", function() {
           console.log("MOUSELEAVE");
});

我不清楚事件委托应该从 在 DOM 中应该高于目标元素的节点完成。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你应该委托这个事件,你可以使用on()方法,试试下面的方法:

    $(document).on('mouseenter', ".collection_add_to", function() { 
         $(this).find( ".playlists" ).fadeIn("fast"); 
    }).on('mouseleave', ".collection_add_to", function() { 
         $(this).find( ".playlists" ).fadeOut("fast"); 
    });
    

    【讨论】:

    • 奇怪,没有调用handlerIn(),而是调用了handlerOut。谢谢!
    • .hover() 有两个函数但.on() 没有,handlerIn 函数将作为事件数据传递
    【解决方案2】:

    您需要使用事件委托,例如。

    $( document ).on('hover', ".collection_add_to", function(e){
        if (e.type == "mouseover") { 
            $(this).find( ".playlists" ).fadeIn("fast"); 
        }
        else if (e.type == "mouseout") { 
            $(this).find( ".playlists" ).fadeOut("fast"); 
        }
    );
    

    $( document ).on( "mouseover", ".collection_add_to" ,
        function() { $(this).find( ".playlists" ).fadeIn("fast"); })
      .on( "mouseout", ".collection_add_to", 
        function() { $(this).find( ".playlists" ).fadeOut("fast"); });
    

    【讨论】:

    • @Raminson .hover() 有两个函数,但 .on() 没有
    【解决方案3】:

    jQuery 只能作用于原始渲染的DOM 而不能与稍后添加的DOM 元素一起作用。

    你可以试试jQuery.delegate()jQuery.on()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多