为什么 jQuery 中的点击事件侦听器存在多种变体?
Why does there exist many variations of the click event listener in jQuery?
到目前为止,我已经找到了四种变体。
addEventListener('click')
是本机方法,性能最佳。
然后 jQuery 将其包装起来以与一些过时的浏览器兼容,同时将性能降低一个数量级,使用三种不同的方法:
on('click')
click()
onclick()
为什么会有这么多?他们存在的history/reasoning是什么?简而言之,它们的用例或限制是否存在差异?
I have found four variations of this so far.
嗯,不。其中两个是 DOM,而不是 jQuery。 jQuery 个实例上没有 addEventListener
或 onclick
。他们在 DOM 个元素上。
那么为什么jQuery两者兼有on
and click
? Maybe the documentation可以告诉我们:
click
This method is a shortcut for .on( "click", handler )
这只是一个快捷方式,七个字符而不是 11 个(最初是 13 个,见下文),因为事件名称在编码时已知(而不是运行时,当我们可能将变量传递给 on
). (还有另一种形式的 click
:如果您不带参数调用它,它会触发事件而不是挂接处理程序。)
你忘记了 bind
, which is an earlier version of on
. on
was added in v1.7 to combine the functionality of bind
, delegate
, and live
. Retrofitting bind
would have required breaking changes, and the word bind
was increasingly coming to mean something else entirely。所以他们使用 on
,因为 DOM 使用 "on" 前缀(onclick
、onmousemove
、onfocus
、...),两者在 DOM 元素属性中,您可以为其分配函数,并且作为属性,您可以将代码放入标记中。
jQuery 也有 one
,这与 on
类似,但会在首次使用时自动删除处理程序。
底线:所有 API 都会随着时间的推移而发展。
到目前为止,我已经找到了四种变体。
addEventListener('click')
是本机方法,性能最佳。
然后 jQuery 将其包装起来以与一些过时的浏览器兼容,同时将性能降低一个数量级,使用三种不同的方法:
on('click')
click()
onclick()
为什么会有这么多?他们存在的history/reasoning是什么?简而言之,它们的用例或限制是否存在差异?
I have found four variations of this so far.
嗯,不。其中两个是 DOM,而不是 jQuery。 jQuery 个实例上没有 addEventListener
或 onclick
。他们在 DOM 个元素上。
那么为什么jQuery两者兼有on
and click
? Maybe the documentation可以告诉我们:
click
This method is a shortcut for
.on( "click", handler )
这只是一个快捷方式,七个字符而不是 11 个(最初是 13 个,见下文),因为事件名称在编码时已知(而不是运行时,当我们可能将变量传递给 on
). (还有另一种形式的 click
:如果您不带参数调用它,它会触发事件而不是挂接处理程序。)
你忘记了 bind
, which is an earlier version of on
. on
was added in v1.7 to combine the functionality of bind
, delegate
, and live
. Retrofitting bind
would have required breaking changes, and the word bind
was increasingly coming to mean something else entirely。所以他们使用 on
,因为 DOM 使用 "on" 前缀(onclick
、onmousemove
、onfocus
、...),两者在 DOM 元素属性中,您可以为其分配函数,并且作为属性,您可以将代码放入标记中。
jQuery 也有 one
,这与 on
类似,但会在首次使用时自动删除处理程序。
底线:所有 API 都会随着时间的推移而发展。