gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:38:03 25 4
gpt4 key购买 nike

我急于想弄清楚为什么 mouseover 事件不能与 .on 处理程序一起使用,并使用来自 ajax 的动态创建的元素。唯一似乎有效的是带有 .live 的代码,但我知道它已被弃用。

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

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

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

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

最佳答案

使用 .on 为新生成的元素添加动态事件委托(delegate) http://api.jquery.com/on/ - 你的主要选择器是一个存在的static parent:

$(".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 ready 函数

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

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

});

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com