gpt4 book ai didi

javascript - 当某个函数运行时删除事件监听器

转载 作者:行者123 更新时间:2023-12-01 00:40:47 25 4
gpt4 key购买 nike

我有以下代码:

function setEvents() {
// do some code
myValidation();
}

function myValidation() {
// do some checks
// if checks passed, then set the values to URL parameters
window.location.replace(window.location.href + "?myName=" + capture_name);
}

setEvents();

$( "#edit-submitted-name-consolidation" ).click(function() {

window.addEventListener("beforeunload", function(e){
(e || window.event).returnValue = setEvents();
}, false);

});

说明:

上面的代码调用了 setEvent() 函数,该函数从内部调用 myValidation() 函数。

此外,我有一个代码 beforeunload ,用于在用户关闭浏览器时运行相同的函数。仅当单击某个输入时才会发生这种情况。

但是,我希望 myValidation() 不要在 beforeunload 运行此操作。

换句话说,我希望浏览器始终运行 beforeunload ,但是当调用/使用 myValidation() 时, beforeunload code> 应该被删除。

为了实现这一目标,这就是我尝试过的:

function setEvents() {
// do some code
myValidation();
}

function myValidation() {
// do some checks
// if checks passed, then set the values to URL parameters
window.removeEventListener("beforeunload",(e));
window.location.replace(window.location.href + "?myName=" + capture_name);
}

setEvents();

$( "#edit-submitted-name-consolidation" ).click(function() {
window.addEventListener("beforeunload", function(e){
(e || window.event).returnValue = setEvents();
}, false);
});

因此,我在 myValidation() 中添加了 window.removeEventListener("beforeunload",(e));。但是,这对我不起作用。

那么请问,如果使用 myValidation() ,如何删除 beforeunload

最佳答案

问题是你应该将处理程序提取到一个变量中,因为这是两个独立的函数,你必须有对原始函数的引用,你不能像这样删除监听器。

您现在正在做的是删除不存在的事件监听器。

const handler = function(e){
(e || window.event).returnValue = setEvents();
}

window.addEventListener("beforeunload", handler, false);
window.removeEventListener("beforeunload", handler);

欲了解更多解释:试试这个=>

const x = () => {}
const y = () => {}

console.log(x === y) // should be true right? wrong. functions are compared by reference.
console.log(x === x) // this is true, since the reference is the same

关于javascript - 当某个函数运行时删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722562/

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