简体   繁体   English

jQuery-.on('click'…)在处理动态创建的元素时不适用于现有元素

[英]jQuery - .on('click' … ) does not work on already existing elements while working on dynamically created ones

javascript: JavaScript的:

$('body').on('click', '.deleteButton > a', function() {
    alert('pop');
    return false;
});

html: HTML:

<div class="deleteButton">
    <a href="#">✖</a>
</div>

This type of binding the click event is working well on newly created elements (via .clone and .prepend), but not working on already existing ones. 这种绑定的click事件在新创建的元素上(通过.clone和.prepend)运行良好,但不适用于现有元素。

But using .click() instead of .on() is working on already existing elements while not working on newly created. 但是使用.click()而不是.on()可以处理现有元素,而不能处理新创建的元素。

Is there any way to bind a click event both on new and already existing elements with one line? 有什么方法可以将一行新的和现有元素上的click事件绑定在一起?

Well you can just have a look at the fiddle JsFiddle 好吧,你可以看看小提琴JsFiddle

$('body').on('click', '.deleteButton > a', function () {});

What you need to do is to attach the event to the body instead of the classes or id's. 您需要做的是将事件附加到正文,而不是类或id。 Doing this will bind your event to the body and in return all the body elements will automatically bind to this event. 这样做会将您的事件绑定到主体,作为回报,所有主体元素将自动绑定到该事件。

Your code is working fine. 您的代码运行正常。 But still you can try this one. 但是您仍然可以尝试这一方法。 It also worked. 它也起作用。

$('.deleteButton > a').on('click', function () {
alert('pop');
return false;
});

Use 采用

            $(document).ready(function(){
            $('body').on('click', '.deleteButton > a', function() {
                alert('pop');
                return false;
            });
            });

Hope this will help you. 希望这会帮助你。

check this jsFiddle 检查这个jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM