jQuery hover、mouseenter和mouseleave在.appendTo后不起作用

7

我在$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"); }
    );
}

什么都没用,新添加的内容上 hover 事件不再起作用。使用 $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结构上更高的节点进行。

3个回答

11

你应该使用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 被调用了。谢谢! - user1283043
1
.hover() 接受两个函数,但 .on() 不接受。handlerIn 函数将作为事件数据传递。 - Musa

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"); });

2
@Raminson。.hover()需要两个函数,但是.on()不需要。 - Musa

0

jQuery只能在最初渲染的DOM中操作,而不能处理后来添加的DOM元素。

您可以尝试使用jQuery.delegate()jQuery.on()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接