简体   繁体   中英

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

javascript:

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

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.

But using .click() instead of .on() is working on already existing elements while not working on newly created.

Is there any way to bind a click event both on new and already existing elements with one line?

Well you can just have a look at the fiddle 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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