jQuery单击处理程序功能不会在DOM加载后添加的元素上触发 [英] jQuery click handler function does not fire on element added after DOM load

查看:58
本文介绍了jQuery单击处理程序功能不会在DOM加载后添加的元素上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我可以使用.live做到这一点,但该方法已被弃用.这是问题所在:

I believe I could do this with .live but that method is deprecated. Here's the issue:

我有一个单击处理程序函数,该函数应在例如"myClickEl"类的任何元素上触发.这在文档加载时在文档中存在的"myClickEl"元素上很好用.但是,如果在DOM加载后添加myClickEl元素,则不会触发点击处理程序.

I have a click handler function that should fire on any element with the class "myClickEl" for example. This works fine on "myClickEl" elements that are present in the document at the time its loaded. However, if I add a myClickEl element after the DOM has loaded, the click handler does not fire.

这是代码.我已经尝试过以下两种方法:

Here's the code. I've tried both methods below:

选项1:

    jQuery('.myClickEl').on('click', function(){
        var formText='This is some text to paste';
        jQuery(this).parent().next('textarea').val('');
        jQuery(this).parent().next('textarea').val(formText);
    });

选项2:

    jQuery('.myClickEl').click(function(){
        var formText='This is some text to paste';
        jQuery(this).parent().next('textarea').val('');
        jQuery(this).parent().next('textarea').val(formText);
    });

推荐答案

您需要使用 事件委托

You need to use Event delegation

jQuery(document).on('click','.myClickEl', function() { 
    var formText='This is some text to paste';
    jQuery(this).parent().next('textarea').val('');
    jQuery(this).parent().next('textarea').val(formText);
});

这篇关于jQuery单击处理程序功能不会在DOM加载后添加的元素上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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