Var*_*ain 9 javascript browser jquery
我试图使用jquery的unbind函数从window对象中删除blur和focus事件监听器:
function removeWindowEvents(){
$(window).unbind('blur') ;
$(window).unbind('focus') ;
}
Run Code Online (Sandbox Code Playgroud)
我使用Javascript注册了活动:
function addEvents(){
window.addEventListener('blur', function(){ document.title = "Blurred" ; });
window.addEventListener('focus', function(){ document.title = "In Focus" ;});
}
Run Code Online (Sandbox Code Playgroud)
然而,这不起作用.我究竟做错了什么?我测试的是Mozilaa和Chrome(最新版本)
你不能按自己的方式去做.
如果使用jQuery配置原始侦听器,jQuery只能取消绑定给定事件的所有事件处理程序.
这是因为addEventListener()必须删除添加的事件,removeEventListener()并且removeEventListener()需要第二个参数来指定回调函数.
从MDN页面:
target.removeEventListener(type, listener[, useCapture])
Run Code Online (Sandbox Code Playgroud)
如果事件最初是使用jQuery注册的,那么jQuery通过只有一个使用addEventListener注册的主事件指向它自己的回调函数然后使用它自己的事件调度到通过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);
}
Run Code Online (Sandbox Code Playgroud)
使用jQuery,你可以这样做:
function addEvents(){
$(window).on('blur', function(){ document.title = "Blurred" ; })
.on('focus', function(){ document.title = "In Focus" ;});
}
function removeWindowEvents() {
$(window).off('blur focus');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18487 次 |
| 最近记录: |