就性能而言,下列两者之间的收益(或仅仅是差异)是什么:
$('.myEl').click();
还有
$('.myEl').trigger('click');
Are there any at all?
检查 http://api.jquery.com/click/:
在第三个变体中,如果在没有参数的情况下调用. click () ,则 is a shortcut for .trigger("click").
看起来他们是一样的。
关于性能方面的问题,请点击这里。 < a href = “ http://jsPerf.com/touch-vs-not-touch”rel = “ nofollow”> http://jsperf.com/trigger-vs-not-trigger 两者几乎是相同的... click ()是触发器的简写(‘ click’)。
i think that
因为它节省了一个函数调用,而 $('.myEl').click();只是调用那个函数。查看来自 jQuery 源代码的代码
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 ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : //here they call trigger('click'); if you provide no arguments this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } });
这是 click方法 的代码:
click
jQuery.fn.click = function (data, fn) { if (fn == null) { fn = data; data = null; } return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click"); }
as you can see; if no arguments are passed to the function it will trigger the click event.
使用 .trigger("click")将少调用一个函数。
.trigger("click")
正如@Sandeep 在他的 回答 .trigger("click")中指出的那样:
从1.9.0开始,对 data和 fn的检查移到了 .on函数 :
data
fn
.on
$.fn.click = function (data, fn) { return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click"); }