search

Home  >  Q&A  >  body text

javascript - Please tell me the difference and pros and cons of trigger('click') and click() in jquery.

$('#btn').trigger('click');
$('#btn').click();

Which one of these two click event triggering methods is better?

为情所困为情所困2716 days ago924

reply all(3)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-26 11:00:52

    jquery2 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 );
        };
    });

    It seems that the click execution event implementation of the $ object also calls trigger... so trigger is better? = =||Different ideas from @MockingBird- -

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-26 11:00:52

    trigger() is mainly used to trigger custom events

    $( "#foo" ).on( "custom", function( event, param1, param2 ) {
      alert( param1 + "\n" + param2 );
    });
    $( "#foo").trigger( "custom", [ "Custom", "Event" ] );

    @Dont posted the jquery source code. In fact, .click() also directly calls the .trigger() method, so the performance should be the same.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 11:00:52

    Like jQuery.post() or jQuery.ajax(), which one is better? ?

    You can obviously guess that the post must call ajax, so use ajax? Just because there is one less function call? Then type more words? waste time?

    There is nothing good or bad. You have to think about other aspects. Being concise and easy to understand is also important.

    reply
    0
  • Cancelreply