jQuery off()不删除点击处理程序 [英] jQuery off() not removing click handler
问题描述
我有以下代码:
$(document).ready(function () {
EnableModal();
});
function EnableModal() {
if (isModalEnabled) { return; }
// Initialize modal dialog
// attach modal-container bootstrap attributes to links with .modal-link class.
// when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
}
function DisableModal() {
$('body').off('click', '.modal-link');
}
在某些情况下,我试图将其关闭,因此我打电话给:
I am attempting to turn this off under certain circumstances, so I am calling:
$('body').off('click', '.modal-link');
但是,具有modal-link
类的按钮仍允许单击事件通过.我在开发人员控制台中看不到任何错误.
However, the button with the modal-link
class is still allowing click events through. I see no errors in the developers console.
我已验证它可以正确调用这些函数,并且在我的测试用例中,每个函数仅被调用一次.
I have verified it is calling these correctly and that each is only being called once in my test case.
我在做什么错了?
推荐答案
我之前遇到过此问题.我不确定一开始会发生什么,想知道是否是因为选择器实际上并不相同.我检查了它们,发现它们是相同的,但仍然无法删除事件处理程序.
I met this issue before. I wasn't sure what happened at the very beginning and wonder if it was because the selectors weren't actually the same. I checked them and found out they were the same but still couldn't remove the event handler.
在删除原始函数后,我终于通过提供一个虚拟函数作为事件处理程序来解决了这个问题.
I finally fixed this by giving a dummy function as event handler after I removed the original one.
function DisableModal() {
$('body').off('click', '.modal-link');
$('body').on('click', '.modal-link', () => {});
}
如果您不喜欢lambda表达式,请随意使用ES5版本.
Feel free to use ES5 version if you don't like the lambda expression. as
$('body').on('click', '.modal-link', function(){});
这篇关于jQuery off()不删除点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!