【发布时间】:2012-08-23 16:34:34
【问题描述】:
我的情况是,我进行了很多 ajax 调用来更改 html 的同一部分。这个 html 代表一个网格。在 ajax 调用中更改 html 后,我将事件处理程序附加到网格的事件。当用户单击刷新按钮时,我执行相同的 ajax 调用来设置新的 html 代码,并再次添加一个事件处理程序来监听网格的事件。
如果之前的事件处理程序仍在内存中,我想知道每次刷新网格并添加新的事件处理程序,如果是,在这种情况下最佳做法是什么? (例如,如果在放置新 html 之前存在,则取消绑定事件处理程序)
这是我所做的一个例子:
$.get(this.config.actionLoggingUserListUrl, viewModel, function (data) {
MyNamespace.ui.hideGridAnimation($("#LoggingActionUsersList"));
if (data.success) {
$("#validationSummary").html("");
$("#usersList").html(data.result);
$("#LoggingActionUsersList").click(function() {
console.log("Here is my event handler attached multiple times!");
});
}
else {
$("#validationSummary").html(data.result);
$("#usersList").html("");
}
});
请注意,我在这种情况下所说的事件处理程序是:
$("#LoggingActionUsersList").click(function() {
console.log("Here is my event handler attached multiple times!");
});
【问题讨论】:
-
您肯定会在每次代码运行时将新的事件处理程序添加到已经存在的事件处理程序中。您可以使用“unbind”取消绑定,或者只是跟踪处理程序是否已经绑定。
-
jQuery
.html()从被.html()替换的元素中隐式清除所有 (jQuery) 处理程序和 (jQuery) 数据。因此,如果您要附加处理程序的这个元素被上面的.html()调用替换,那么您不需要显式分离它。
标签: javascript jquery ajax javascript-events event-handling