gpt4 book ai didi

javascript - jQuery off() 不删除点击处理程序

转载 作者:行者123 更新时间:2023-12-03 08:27:35 24 4
gpt4 key购买 nike

我有以下代码:

$(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');
}

我试图在某些情况下关闭此功能,因此我调用:

$('body').off('click', '.modal-link');

但是,具有 modal-link 类的按钮仍然允许点击事件通过。我在开发者控制台中没有看到任何错误。

我已经验证它正确地调用了这些,并且每个在我的测试用例中只被调用一次。

我在这里做错了什么?

最佳答案

我以前也遇到过这个问题。我不确定一开始发生了什么,想知道是否是因为选择器实际上并不相同。我检查了它们,发现它们是相同的,但仍然无法删除事件处理程序。

在删除原始函数后,我最终通过提供一个虚拟函数作为事件处理程序解决了这个问题。

function DisableModal() {
$('body').off('click', '.modal-link');
$('body').on('click', '.modal-link', () => {});
}

如果您不喜欢 lambda 表达式,请随意使用 ES5 版本。作为

$('body').on('click', '.modal-link', function(){});

关于javascript - jQuery off() 不删除点击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33484369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com