我正在绞尽脑汁地试图找出为什么鼠标悬停事件不能与带有 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/