使用jQuery从窗口对象中删除事件侦听器 [英] Remove event listener from window object using jquery

查看:1001
本文介绍了使用jQuery从窗口对象中删除事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用jquery的unbind函数从窗口对象中删除blurfocus事件监听器:

I am trying to remove blur and focus event listeners from window object using jquery's unbind function using:

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

我使用Javascript注册了该活动:

I registered the event using Javascript:

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


}

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

This however does not work. What am I doing wrong? I tested this is Mozilaa and Chrome(latest versions)

推荐答案

您无法按自己的方式做.

You can't do it your way.

如果原始侦听器是使用jQuery配置的,则jQuery只能解除给定事件的所有事件处理程序的绑定.

jQuery can only unbind all event handlers for a given event if the original listeners were configured using jQuery.

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

This is because an event that is added with addEventListener() must be removed with removeEventListener() and removeEventListener() requires a second argument that specifies the callback function.

MDN页面中:

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

如果该事件最初是使用jQuery注册的,则jQuery可以通过仅在addEventListener中注册一个指向其自己的回调函数的主事件,然后将其自身的事件分配给通过jQuery注册的所有事件来解决此问题.这样一来,它就可以像您尝试使用的那样支持通用.unbind(),但是只有在原始事件已向jQuery注册并通过jQuery事件处理程序管理系统的情况下,它才有效.

If the event is originally registered using jQuery, jQuery works around this by having only one master event registered with addEventListener that points to it's own callback function and then using it's own event dispatching to all the events registered via jQuery. This allows it to support generic .unbind() like you're trying to use, but it will only work if the original event is registered with jQuery and thus goes through the jQuery event handler management system.

因此,如果没有jQuery,您将像这样进行操作:

So, without jQuery, you would do it like this:

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,您可以这样做:

With jQuery, you could do it like this:

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

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

这篇关于使用jQuery从窗口对象中删除事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆