使用jQuery将事件侦听器添加到动态添加的元素中
问题描述:
现在,我了解到要将事件侦听器附加到动态的元素上,您必须在添加该元素后重新定义侦听器.
So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.
是否有任何方法可以绕过此操作,因此您不必执行额外的全部代码块?
Is there any way to bypass this, so you don't have to execute a whole extra block of code?
答
使用 .on()
您一次可以定义您的函数,它将对任何动态添加的元素执行.
Using .on()
you can define your function once, and it will execute for any dynamically added elements.
例如
$('#staticDiv').on('click', 'yourSelector', function() {
//do something
});