就绩效而言,:
之间的收益(或差异)是什么?$('.myEl').click();
和
$('.myEl').trigger('click');
有没有?
答案 0 :(得分:55)
This is the code for the click
method:
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");
}
你可以看到;如果没有参数传递给函数,它将触发click事件。
使用.trigger("click")
会减少一个功能。
正如@Sandeep在answer .trigger("click")
指出的更快:
As of 1.9.0 the check for data
and fn
has been moved to the .on
function:
$.fn.click = function (data, fn) {
return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click");
}
答案 1 :(得分:3)
表示性能。检查这里.. http://jsperf.com/trigger-vs-not-trigger 两者几乎相同... click()是触发器的简写('click')。
答案 2 :(得分:3)
我认为
$('.myEl').trigger('click');
更好,因为它会为您调用函数调用$('.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;
}
});
答案 3 :(得分:2)