守着星空守着你
有时这样做(最高投票的答案)并不总是足够的:$('body').on('click', 'a.myclass', function() {
// do something});这可能是一个问题,因为触发了订单事件处理程序。如果你发现自己这样做了,但由于它的处理顺序而导致问题。你总是可以将它包装到一个函数中,当被称为“刷新”监听器时。例如:function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}}因为它是一个函数,每当我以这种方式设置我的监听器时,我通常会在文档就绪时调用它:$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();});然后,每当您添加一些动态添加的元素时,再次调用该方法:function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();}希望这有帮助!问候,