jQuery的鼠标悬停不工作与动态创建的元素 [英] Jquery mouseover not working with dynamically created element

查看:186
本文介绍了jQuery的鼠标悬停不工作与动态创建的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拉我的头发试图找出为什么鼠标悬停事件不会对。对处理程序从阿贾克斯动态创建的元素工作。这似乎工作的唯一的事情就是code与.live但据我所知,这是pcated德$ P $。

  $(下拉UL李)。生活(鼠标悬停功能(){
警报('鼠标悬停工程);
});
 

然而,当我尝试使用。对,这是行不通的 - 无论我尝试什么样的变化(的document.ready,.mouseover,等等等等)

  $(下拉UL丽)。在(鼠标悬停功能(){
警报('鼠标悬停工程);
});
 

事件处理程序是在的code的底部,所以他们最后执行。任何人有什么我做错了?

一个想法
解决方案

  $(下拉列表中)。在(鼠标悬停,礼,函数(){
   警报('鼠标悬停作品!!!!!!!!!');
});
 

使用。对对新生成的元素 - 你需要将事件委托给你的元素:

  $(父元素)。在(事件,事件委派的元素,函数(){
 

阅读文档! http://api.jquery.com/on/

  

委派事件具有的优点是,它们可以处理从被添加到文档在稍后的时间派生元素事件。通过采摘保证是present在委派的事件处理程序连接时的元素,你可以使用委派的事件,以避免需要频繁安装和取下事件处理程序。此元件可以是在模型 - 视图 - 控制器设计的视图的容器元素,例如,或文件,如果事件处理要监视文档中的所有事件冒泡。文档元素是在文档的头部可装载任何其他HTML之前,因此它是安全的,有附加的事件,而无需等待的文件成为就绪

修改请务必妥善包裹你的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/

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.

edit make sure you wrapped properly your code! (:

(function($){

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

})(jQuery);

http://jsfiddle.net/roXon/MAL7a/

这篇关于jQuery的鼠标悬停不工作与动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆