使用 jQuery's $().on('mouseenter',function(){}) 比 $().mouseenter(function(){}) 有优势吗? [英] Is there an advantage to using jQuery's $().on('mouseenter',function(){}) over $().mouseenter(function(){})?
问题描述
我经常看到这样的代码:
I frequently see code like:
$("#thing").on("mouseenter",function(){ Do stuff });
就我个人而言,我几乎总是这样写:
Personally, I almost always write:
$("#thing").mouseenter(function(){ Do stuff });
同样的,我也经常写
$("#thing").click(function(){})
但我已经看到人们更正它(是的,我知道在 v. 1.7+ 中 on
比 bind
更受欢迎,所以它本质上是相同的偏好问题):
but I have seen people correct it to (yes, I know on
is preferred over bind
in v. 1.7+, so it's essentially the same preference issue):
$("#thing").bind("click",function(){})
我是否做错了什么,我没有看到的两个功能之间是否存在很大差异?它似乎总是做我想做的事,所以这从来都不是一个实际问题,但我很想知道是否有我忽略的理论考虑.
Am I doing something "wrong", is there a deep difference between the two functions that I'm not seeing? It always seems to do what I want it to do, so it's never been a practical concern, but I'd be interested to know if there's a theoretical consideration I'm overlooking.
推荐答案
不是真的,只是因为 mouseenter
函数调用 on
(或 触发器
(如果不带参数调用),如源代码所示:
Not really, it's just a little faster as the mouseenter
function calls on
(or trigger
if called without argument) as can be seen in the source code :
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
如您所见,许多事件也是如此.
As you can see, the same can be said for many events.
就个人而言,当我不需要on
mouseenter(或click
等)功能> :在我看来,使用 jQuery 的一大优势是它使代码不那么冗长且更具可读性.而且我认为你不应该被纠正,问问纠正你的人他为什么这样做.
Personally, I prefer to use the mouseenter
(or click
, etc.) function when I don't need the special features of on
: one of the big advantages in my opinion in using jQuery is that it makes the code less verbose and more readable. And I don't think you should be corrected, ask the guys who corrects you why he does that.
这篇关于使用 jQuery's $().on('mouseenter',function(){}) 比 $().mouseenter(function(){}) 有优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!