Is there any difference between the following code?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
Is there any difference between the following code?
$('#whatever').on('click', function() {
/* your code here */
});
and
$('#whatever').click(function() {
/* your code here */
});
$(document).on('click','.UPDATE',function(){ });
is effectively work like same fetched data by using jquery. button not working at time of update or delete:No, there isn't.
The point of
on()
is its other overloads, and the ability to handle events that don't have shortcut methods.No, there is no functional difference between the two code samples in your question.
.click(fn)
is a "shortcut method" for.on("click", fn)
. From the documentation for.on()
:Note that
.on()
differs from.click()
in that it has the ability to create delegated event handlers by passing aselector
parameter, whereas.click()
does not. When.on()
is called without aselector
parameter, it behaves exactly the same as.click()
. If you want event delegation, use.on()
.I think, the difference is in usage patterns.
I would prefer
.on
over.click
because the former can use less memory and work for dynamically added elements.Consider the following html:
where we add new buttons via
and want "Alert!" to show an alert. We can use either "click" or "on" for that.
When we use
click
with the above, a separate handler gets created for every single element that matches the selector. That means
When we use
.on
with the above, a single handler for all elements that match your selector, including the ones created dynamically.
...another reason to use
.on
As Adrien commented below, another reason to use
.on
is namespaced events.If you add a handler with
.on("click", handler)
you normally remove it with.off("click", handler)
which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:with unbinding via
.on()
is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both.bind()
and.live()
into one function that alters behavior as you pass it different parameters.As you have written your example, there is no difference between the two. Both bind a handler to the
click
event of#whatever
.on()
offers additional flexibility in allowing you to delegate events fired by children of#whatever
to a single handler function, if you choose.