问题描述
我拉我的头发试图找出为什么鼠标悬停事件不会对。对处理程序从阿贾克斯动态创建的元素工作。这似乎工作的唯一的事情就是code与.live但据我所知,这是pcated德$ P $。
$(下拉UL李)。生活(鼠标悬停功能(){
警报('鼠标悬停工程);
});
然而,当我尝试使用。对,这是行不通的 - 无论我尝试什么样的变化(的document.ready,.mouseover,等等等等)
$(下拉UL丽)。在(鼠标悬停功能(){
警报('鼠标悬停工程);
});
事件处理程序是在的code的底部,所以他们最后执行。任何人有什么我做错了?
一个想法 $(下拉列表中)。在(鼠标悬停,礼,函数(){
警报('鼠标悬停作品!!!!!!!!!');
});
使用。对
对新生成的元素 - 你需要将事件委托给你的元素:
$(父元素)。在(事件,事件委派的元素,函数(){
阅读文档! http://api.jquery.com/on/
修改请务必妥善包裹你的code! (:
(功能($){
$(下拉列表中)。在(鼠标悬停,礼,函数(){
警报('鼠标悬停作品!!!!!!!!!');
});
})(jQuery的);
http://jsfiddle.net/roXon/MAL7a/
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??
$(".dropdown").on("mouseover", "li", function() {
alert('mouseover works!!!!!!!!!');
});
Using .on
for newly generated elements - you need to delegate your event to your elements:
$(PARENT-ELEMENT).on(EVENT, EVENT-DELEGATED-ELEMENTS, function(){
Read the DOCS! http://api.jquery.com/on/
edit make sure you wrapped properly your code! (:
(function($){
$(".dropdown").on("mouseover", "li", function() {
alert('mouseover works!!!!!!!!!');
});
})(jQuery);
http://jsfiddle.net/roXon/MAL7a/
这篇关于jQuery的鼠标悬停不工作与动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!