javascript - jQuery ajax 加载或更新后,我丢失了鼠标悬停事件

标签 javascript jquery ajax jquery-events

在使用 .load 更新我的 div 后,即将项目添加到我的列表中,我使用 firebug 并看到列表已更新。但是,我丢失了页面首次加载时有效的 mouseover 事件。在我的脚本 js 中,我有:

// 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();
     })
});

function addItemToDiv(id, ref, num) {
    $("#miniList").load("/list/ajax_updateList.jsp", {
        'action' : 'additem',
        'pid' : id,
        'pref' : ref,
        'qty' : num
    });
}

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

欢迎任何想法。

最佳答案

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

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

api.jquery.com/live

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

如果您使用的是 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
  }
});

关于javascript - jQuery ajax 加载或更新后,我丢失了鼠标悬停事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4363721/

相关文章:

javascript - 从网站获取部分内容到不同的网站

ajax - 在ajax调用上使用jquery更新div而不刷新页面

javascript - 使用 WordPress 发送带有附件的电子邮件

ajax - "Redirect"页面没有刷新(Facebook 照片样式)

javascript - 选择其数据属性中至少有一个值的元素,该元素包含在某个数组中

javascript - 使用 JQuery undefined + null tr​​im(str)!= =""检查数组、对象、字符串的最佳方法是什么?

javascript - InnerHTML 多字段多报错

javascript - 推文引用

javascript - 如何在浏览器调整大小时启用滚动

javascript - jQuery 验证 errorPlacement - 更正后无法删除错误