Is there a difference between the codes A and B below?

Asked

Viewed 53 times

3

Code A

$('#tantoFaz').on('click', function() {
 /* ....... */
});

Code B

$('#tantoFaz').click(function() {
 /* ....... */
});

1 answer

2


In the way presented, there is no difference. In fact, the function itself click can be considered as a shortcut to the function on, with the parameter click, with some caveats. The function click has three variations:

.click(handler)

In which handler is a function that is executed at each event click element. This variation is analogous to be used .on("click", handler), as asked.

.click(eventData, handler)

The second variation takes a parameter eventData a further. The operation of this variation is also analogous to the use of the function on, although the data reported in eventData will be passed as a parameter to handler when the event is triggered.

.click()

The third variation, without parameters, is the one that should be taken care in this comparison, because its use is not similar to the function on. What she does, in fact, is trigger the event click of the element in question, performing all the functions defined by the previous variations. This variation is analogous to the .trigger("click").

Therefore there is no difference between the codes shown in the question.

Reference: Official documentation

  • +1! "A contribution addition that is not worth adding as a response": In cases of elements created dynamically, the event .click() will not work as expected, for that we would have to use the .on('click'). example in jsFiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.