jQuery选择器选择执行代码时DOM中存在的匹配元素,并且不会动态更新。当您调用一个函数(例如
.hover()添加事件处理程序)时,它只会将它们添加到那些元素中。进行AJAX调用并替换页面的一部分时,您将使用绑定到它们的事件处理程序删除这些元素,并用新元素替换它们。即使这些元素现在与该选择器匹配,它们也不会绑定事件处理程序,因为执行该操作的代码已经执行。
事件处理程序
专门针对事件处理程序(即
.click()),您可以使用事件委托来解决此问题。基本原理是将事件处理程序绑定到静态元素(页面加载时存在,永远不会被替换)中,该元素将包含所有动态内容(加载AJAX)。您可以在jQuery文档中阅读有关事件委托的更多信息。
对于您的
click事件处理程序,更新后的代码如下所示:
$(document).on('click', "#click", function () { $('#click').css({ "background-color": "#f00", "color": "#fff", "cursor": "inherit" }).text("Open this window again and this message will still be here."); return false;});这样会将事件处理程序绑定到整个文档(因此在页面卸载之前永远不会删除它),它将对
click具有
id属性的元素上的事件做出反应
click。理想情况下,您将使用更接近DOM中动态元素的内容(也许
<div>页面上始终存在一个动态元素,并包含所有页面内容),因为这样可以提高效率。
不过,问题出在您需要处理
.hover()时。
hoverJavascript中没有实际的事件,jQuery只是将该函数提供为将事件处理程序绑定到
mouseenter和
mouseleave事件的便捷速记。但是,您可以使用事件委托:
$(document).on({ mouseenter: function () { $(this).stop().animate({ width: xwidth * 3, height: xheight * 3, margin: -(xwidth / 3) }, 200); //END FUNCTION $(this).addClass('image-popout-shadow'); }, mouseleave: function () { $(this).stop().animate({ width: xwidth, height: xheight, margin: 0 }, 200, function () { $(this).removeClass('image-popout-shadow'); }); //END FUNCTION }}, '.image-popout img');jQuery插件
这涵盖了事件处理程序绑定。但是,这还不是您要做的全部。您还初始化了一个jQuery插件(colorbox),无法将它们委托给元素。加载AJAX内容后,您只需再次调用这些行即可。最简单的方法是将它们移到一个单独的命名函数中,然后可以在两个地方(在页面加载和AJAX请求
success回调中)调用它们:
function initialiseColorbox() { $(".iframe").colorbox({ iframe: true, width: "1000px", height: "500px" }); $(".inline").colorbox({ inline: true, width: "50%" }); $(".callbacks").colorbox({ onOpen: function () { alert('onOpen: colorbox is about to open'); }, onLoad: function () { alert('onLoad: colorbox has started to load the targeted content'); }, onComplete: function () { alert('onComplete: colorbox has displayed the loaded content'); }, onCleanup: function () { alert('onCleanup: colorbox has begun the close process'); }, onClosed: function () { alert('onClosed: colorbox has completely closed'); } });}


