本文介绍了与$().mouseenter(function(){})相比,使用jQuery的$().on('mouseenter',function(){})有优势吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到类似这样的代码:

I frequently see code like:

$("#thing").on("mouseenter",function(){ Do stuff });

我个人几乎总是写:

$("#thing").mouseenter(function(){ Do stuff });

类似地,我经常写

$("#thing").click(function(){})

但是我看到人们对其进行了纠正(是的,我知道on在1.7+版本中比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(如果不带参数调用,则调用trigger)的速度稍快一些,如源代码:

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.

这篇关于与$().mouseenter(function(){})相比,使用jQuery的$().on('mouseenter',function(){})有优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:06