jQuery .on() event doesn't work for dynamically added element

后端 未结 3 1367
轮回少年
轮回少年 2020-12-05 15:44

I\'m making a project where a whole div with buttons is being inserted dynamically when user click a button, and inside that div there\'s a button, which when the user click

相关标签:
3条回答
  • 2020-12-05 16:09

    It does not look like div.mainTaskWrapper exist.

    From the documentation (yes, it is actually bold):

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.

    [...]

    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.

    You might want to bind it to #tasksWrapper instead:

    $("#tasksWrapper").on('click', '.checkButton' , function(){
        alert("test text");
    });
    
    0 讨论(0)
  • 2020-12-05 16:10

    I know this is an old post but might be useful for anyone else who comes across...

    You could try:

    jQuery('body')on.('DOMNodeInserted', '#yourdynamicallyaddeddiv', function () {
    //Your button click event
    });
    

    Here's a quick example - https://jsfiddle.net/8b0e2auu/

    0 讨论(0)
  • 2020-12-05 16:13

    You need to specify a selector with on (as a parameter) to make it behave like the old delegate method. If you don't do that, the event will only be linked to the elements that currenly match div.mainTaskWrapper (which do not exists yet). You need to either re-assign the event after you added the new elements, or add the event to an element that already exists, like #tasksWrapper or the document itself.

    See 'Direct and delegate events' on this page.

    0 讨论(0)
提交回复
热议问题