在jQuery ajax加载或更新后,我丢失了mouseover事件

ish*_*dev 5 javascript ajax jquery javascript-events

在使用.load更新我的div后,即将项添加到我的列表中,我使用了firebug并看到列表已更新.但是,我丢失了鼠标悬停事件,该事件在页面首次加载时起作用....在我的脚本中我有:

// hide and show are css classes that display none and block respectively

function openList(){
    $("#miniList").removeClass().addClass("show");
}
function closeList(){
    $("#miniList").removeClass().addClass("hide");
}
...
$(document).ready(function() {
    $("#miniList").mouseover(function() {
        openList();
    })
    $("#miniList").mouseout(function() {
        closeList();
     })
});
Run Code Online (Sandbox Code Playgroud)
function addItemToDiv(id, ref, num) {
    $("#miniList").load("/list/ajax_updateList.jsp", {
        'action' : 'additem',
        'pid' : id,
        'pref' : ref,
        'qty' : num
    });
}
Run Code Online (Sandbox Code Playgroud)

...当然,这在第一次加载页面时工作正常,但是当我将项目添加到列表时,DOM会更新,但鼠标悬停效果不再起作用.

任何想法都受到欢迎.提前谢谢了.

kob*_*obe 2

对于动态添加的 DOM 元素,您需要使用 jquery.live()函数。

请浏览以下链接,我认为这可能会解决您的问题:

api.jquery.com/live

@ishwebdev,这是我们运行时的常见问题,对于页面加载后添加的所有 DOM 元素(如运行时),我们需要通过实时绑定事件而不是常规绑定

如果您使用的是 jquery 1.4,请使用以下代码:

// 来自jquery.com

$('give your selector here').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});
Run Code Online (Sandbox Code Playgroud)