问题描述
我想知道为什么以下代码在某些浏览器中有效?即即使没有 click()
函数的参数,但事件
变量存在且 dosomething
在事件触发器对象上调用方法?
I wonder why does the following code work in some browsers? I.e. even when there's no parameter to a click()
function however event
variable exists and dosomething
method is called on the event trigger object?
$(<selector>).click(function () {
$(event.target).<dosomething>
});
推荐答案
它不可靠。例如,该代码将在Firefox上失败。
It isn't, reliably. That code will fail on Firefox, for instance.
Microsoft使用全球 事件
变量。 DOM2将其定义为处理程序的参数。 Chrome决定将特定于MS的代码作为一个骨头并同时执行这两项操作。 Firefox没有。
Microsoft used a global event
variable. DOM2 defined it as an argument to the handler. Chrome decided to throw MS-specific code a bone and do both. Firefox did not.
即使在代码有效的浏览器上,请注意事件
将是原始事件对象,而不是jQuery增强的。这意味着,例如,在IE8上,您无法调用 event.preventDefault
,因为IE8不提供该功能。 jQuery如果你接受了这个参数,因为jQuery提供了一个具有标准化功能的事件对象,即使在缺少这些功能的浏览器上也是如此。
Even on the browsers where that code works, note that event
will be a raw event object, not the jQuery-enhanced one. That means that, for instance, on IE8 you can't call event.preventDefault
because IE8 doesn't supply that function. jQuery would if you accepted the argument, because jQuery provides an event object with standardized features even on browsers that are missing those features.
这篇关于为什么即使未作为参数传递,'event'变量也可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!