使用jQuery自动将事件处理程序添加到新创建的元素中 [英] Automatically add an event handler to a newly created element using jQuery

查看:79
本文介绍了使用jQuery自动将事件处理程序添加到新创建的元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在准备好文档后,我将此事件处理程序附加到带有bubbleItemOff类的所有元素上. 我的问题是,触发文档就绪事件后,会动态创建某些bubbleItemOff元素.

On document ready I attach this event handler to all elements with class bubbleItemOff. My problem is that some of the bubbleItemOff elements are created dynamically after the document ready event is fired.

是否可以将事件处理程序自动添加到新创建的元素中,或者在元素创建后是否必须显式地添加事件处理程序?

Is there any way to automatically add the event handler to the newly created elements, or do I have to explicitly do it after the element is created?

  $(function() {
      $('.bubbleItemOff').mouseenter(function(e) 
       {
          //...
       });
   });

推荐答案

例如,使用on()方法在公共父元素上使用事件委托(假设您使用的是jQuery 1.7.x +)

Use event delegation on a common parent element using on() method (assuming you're using jQuery 1.7.x +), e.g.

$(function() {
    $('body').on('mouseenter', '.bubbleItemOff', function(e) 
    {
     ...
    }
}

如果您使用的是旧版本,请改用delegate().用.bubbleItemOff

if you're using an older version use delegate() instead. Change body with the first common parent element of .bubbleItemOff

这篇关于使用jQuery自动将事件处理程序添加到新创建的元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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