我在$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结构上更高的节点进行。
.hover()
接受两个函数,但.on()
不接受。handlerIn 函数将作为事件数据传递。 - Musa