jQuery $(window).blur与本机window.onblur [英] jQuery $(window).blur vs native window.onblur

查看:638
本文介绍了jQuery $(window).blur与本机window.onblur的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery的优势

$(window).blur(function() { ... })

附加事件处理程序,而不是直接用

设置事件处理程序

window.onblur = function() { ... }

后者似乎不那么健壮,因为它仅支持一个模糊处理程序,并且当与其他程序包一起使用时,其他代码可能会使用另一个函数覆盖window.blur值.但是,jQuery实现也不会发生这种情况,因为它大概使用window.blur作为其基础实现?

一些人还提到了window.addEventListener替代方法,除了上述方法之外,该替代方法还可用于添加'onblur'事件.

解决方案

$(window).blur(function() { ... })

允许您添加一个或多个事件处理程序.


window.onblur = function() { ... }

让您只有一个事件处理程序来处理模糊事件.


前者使用jQuery自己的事件处理机制.对.blur()的调用将委派给jQuery.fn.on(),后者又将委派给jQuery.event.add.此add()方法将为给定的事件类型创建自己的处理程序,并在触发给定类型的事件时告诉addEventListener()调用此处理程序.因此,基本上jQuery具有它自己的事件处理方式,它依靠addEventListener()正确执行.

后者只是一个只能包含一个值的属性,因此无法对事件处理程序进行排队.

我写了一点示范来证明这一点: http://jsfiddle.net/GnNZm/1/

What are the advantages of using jQuery's

$(window).blur(function() { ... })

to attach an event handler versus setting it directly with

window.onblur = function() { ... }

It seems that the latter is less robust because it only supports one blur handler, and when used with other packages, other code might override the window.blur value with another function. However, couldn't this also happen with the jQuery implementation too, which presumably uses window.blur as its underlying implementation?

EDIT: Several people have also mentioned the window.addEventListener alternative, which can be used to add an 'onblur' event apart from the methods above.

解决方案

$(window).blur(function() { ... })

Lets you add one or more event handlers.


window.onblur = function() { ... }

Lets you only have one event handler handling the blur event.


The former uses the jQuery's own event handle mechanism. The call to .blur() will delegate to jQuery.fn.on() which in turn will delegate to jQuery.event.add. This add() method will create it's own handler for the given event type and tell addEventListener() to call this handler whenever a event of given type is fired. So basically jQuery has it's own way of event handling which relies on addEventListener() to execute properly.

The latter is just an attribute which can only contain one value so queueing event handlers is impossible.

I wrote a little demonstration to prove this point: http://jsfiddle.net/GnNZm/1/

这篇关于jQuery $(window).blur与本机window.onblur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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