ajax - 事件不适用于动态创建的元素

标签 ajax dynamic event-handling jquery

我正在绞尽脑汁地试图找出为什么鼠标悬停事件不能与带有 ajax 动态创建元素的 .on 处理程序一起使用。唯一有效的似乎是带有 .live 的代码,但我知道它已被弃用。

$(".dropdown ul li").live("mouseover", function() {
alert('mouseover works');
});

但是,当我尝试使用 .on 时,它不会工作 - 无论我尝试什么变体(document.ready、.mouseover 等)

$(".dropdown ul li").on("mouseover", function() {
alert('mouseover works');
});

事件处理程序位于代码的底部,因此它们最后执行。有人知道我做错了什么吗?

最佳答案

通过动态事件委托(delegate)对新生成的元素使用.on http://api.jquery.com/on/ - 您的主选择器是现有的静态父级:

$(".static-parent").on("event1 event2", ".dynamic-child", function() {

或者根据您的情况:

$(".dropdown").on("mouseover", "li", function() {
   alert('mouseover works!!!!!!!!!');
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

还要确保使用DOM 就绪函数

jQuery(function($) { // DOM is now ready and $ alias secured

    $(".dropdown").on("mouseover", "li", function() {
       alert('mouseover works!!!!!!!!!');
    });

});

关于ajax - 事件不适用于动态创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11288516/

相关文章:

c# - 使用 Roslyn 创建部分类 - 一个在运行时编译的类

javascript - 如果 AJAX 请求在上一个请求的 5 秒内,我该如何阻止它?

javascript - http-Get 请求,响应为空

c# - 使用字符串的动态 IQueryable 顺序

jquery - 如何通过 jquery 将 json 响应 Hook 到 html 表单?

c++ - 将 WCHAR 数组作为 LPARAM 发送到 winproc 的正确方法是什么?

javascript - 无法弄清楚为什么我的 change(...) 事件处理程序在这种情况下不起作用

javascript - 我可以通过将所有相同类型的事件组合到一个处理程序中来提高 jQuery 性能吗?

jQuery-最低浏览器内存要求

javascript - jquery进度条setTimeout