事件不能动态创建元素 [英] Event not working on dynamically created element
问题描述
$(。 (mouse);
});
但是,当我尝试使用.on,它将无法正常工作 - 无论我尝试什么变体document.ready,.mouseover等等)
$(。dropdown ul li)。on(mouseover function(){
alert('mouseover works');
});
事件处理程序位于代码的底部,因此最后执行。任何人都知道我在做错什么?
使用 .on
新生成的元素与动态事件委派 http:// api。 jquery.com/on/ - 您的主选择器是现有的静态父:
$(。static-parent)。on(event1 event2,.dynamic-child,function(){
或您的情况:
$(。dropdown)。on ,li,function(){
/ pre>
alert('mouseover works !!!!!!!!!');
});
委托事件的优点是可以处理来自后来添加到文档的后代元素的事件。一个保证在委托事件处理程序附加时出现的元素,您可以使用委托事件来避免f请求附加和删除事件处理程序。该元素可以是Model-View-Controller设计中的视图的容器元素,例如,如果事件处理程序想要监视文档中的所有冒泡事件,则可以是文档。文件元素在加载任何其他HTML之前可以在文档的头部使用,因此可以安全地在那里附加事件,而无需等待文档准备就绪。
还要确保使用 DOM就绪功能
jQuery(function ($){// DOM现在准备好了,$ alias保证
$(。dropdown)。on(mouseover,li,function(){
alert 'mouseover works !!!!!!!!!');
});
});
I'm pulling my hair out trying to figure out why the mouseover event won't work with the .on handler with a dynamically created element from ajax. The only thing that seems to work is the code with .live but I understand that it is deprecated.
$(".dropdown ul li").live("mouseover", function() { alert('mouseover works'); });
However, when I try using .on, it will not work - no matter what variations I try (document.ready, .mouseover, etc etc)
$(".dropdown ul li").on("mouseover", function() { alert('mouseover works'); });
The event handlers are at the bottom of the code, so they are executed last. Anyone have an idea of what I'm doing wrong??
解决方案Using
.on
for newly generated elements with dynamic event delegation http://api.jquery.com/on/ - where your main selector is an existent static parent:$(".static-parent").on("event1 event2", ".dynamic-child", function() {
or in your case:
$(".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.
Also make sure to use a DOM ready function
jQuery(function($) { // DOM is now ready and $ alias secured $(".dropdown").on("mouseover", "li", function() { alert('mouseover works!!!!!!!!!'); }); });
这篇关于事件不能动态创建元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!