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

后端 未结 3 1373
轮回少年
轮回少年 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: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.

提交回复
热议问题