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

后端 未结 3 1378
轮回少年
轮回少年 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");
    });
    

提交回复
热议问题