gpt4 book ai didi

javascript - 使用 jquery 从 window 对象中删除事件监听器

转载 作者:行者123 更新时间:2023-11-28 03:33:25 24 4
gpt4 key购买 nike

我正在尝试使用 jquery 的取消绑定(bind)函数从窗口对象中删除 blurfocus 事件监听器:

function removeWindowEvents(){
$(window).unbind('blur') ;
$(window).unbind('focus') ;
}

我使用 Javascript 注册了该事件:

function addEvents(){
window.addEventListener('blur', function(){ document.title = "Blurred" ; });
window.addEventListener('focus', function(){ document.title = "In Focus" ;});


}

但这不起作用。我究竟做错了什么?我测试的是 Mozilaa 和 Chrome(最新版本)

最佳答案

你不能按照自己的方式去做。

如果原始监听器是使用 jQuery 配置的,则 jQuery 只能取消绑定(bind)给定事件的所有事件处理程序。

这是因为使用 addEventListener() 添加的事件必须使用 removeEventListener() 删除,并且 removeEventListener() 需要第二个指定回调函数的参数。

来自MDN page :

target.removeEventListener(type, listener[, useCapture])

如果事件最初是使用 jQuery 注册的,则 jQuery 会通过仅使用指向其自己的回调函数的 addEventListener 注册一个主事件来解决此问题,然后使用其自己的事件分派(dispatch)到通过 jQuery 注册的所有事件。这使得它能够像您尝试使用的那样支持通用 .unbind() ,但只有当原始事件注册到 jQuery 并通过 jQuery 事件处理程序管理系统时它才会起作用。

所以,如果没有 jQuery,你会这样做:

function blurHandler() {
document.title = "Blurred" ;
}

function focusHandler() {
document.title = "In Focus" ;
}

function addEvents(){
window.addEventListener('blur', blurHandler);
window.addEventListener('focus', focusHandler);
}

function removeWinowEvents() {
window.removeEventListener('blur', blurHandler);
window.removeEventListener('focus', focusHandler);
}

使用 jQuery,你可以这样做:

function addEvents(){
$(window).on('blur', function(){ document.title = "Blurred" ; })
.on('focus', function(){ document.title = "In Focus" ;});
}

function removeWindowEvents() {
$(window).off('blur focus');
}

关于javascript - 使用 jquery 从 window 对象中删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946186/

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