jQuery - Calling .trigger('click') vs .click()

后端 未结 2 1354
一向
一向 2020-12-10 15:19

In jQuery what is the better way to trigger an event such as click? Using the .trigger(\'click\') function or calling .click()?

I have alwa

2条回答
  •  不思量自难忘°
    2020-12-10 15:31

    If you're using .trigger() you have the advantage of being able to pass additional parameters, whereas .click() must be called without any.

    Taken from the documentation:

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

    'Custom' and 'Event' are being passed to the event handler as param1 and param2 respectively

    Besides that, the .click() is unlike other functions that implement get / set based on the number of arguments, because it implements trigger / set instead. Using a dedicated .trigger(), to me, is more logical.

提交回复
热议问题