jquery - Difference between .on('click') vs .click() -
is there difference between following code?
$('#whatever').on('click', function() { /* code here */ });
and
$('#whatever').click(function() { /* code here */ });
i think, difference in usage patterns.
i prefer .on
on .click
because former can use less memory , work dynamically added elements.
consider following html:
<html> <button id="add">add new</button> <div id="container"> <button class="alert">alert!</button> </div> </html>
where add new buttons via
$("button#add").click(function() { var html = "<button class='alert'>alert!</button>"; $("button.alert:last").parent().append(html); });
and want "alert!" show alert. can use either "click" or "on" that.
when use click
$("button.alert").click(function() { alert(1); });
with above, separate handler gets created every single element matches selector. means
- many matching elements create many identical handlers , increase memory footprint
- dynamically added items won't have handler - ie, in above html newly added "alert!" buttons won't work unless rebind handler.
when use .on
$("div#container").on('click', 'button.alert', function() { alert(1); });
with above, single handler all elements match selector, including ones created dynamically.
...another reason use .on
as adrien commented below, reason use .on
namespaced events.
if add handler .on("click", handler)
remove .off("click", handler)
remove handler. works if have reference function, if don't ? use namespaces:
$("#element").on("click.somenamespace", function() { console.log("anonymous!"); });
with unbinding via
$("#element").off("click.somenamespace");
Comments
Post a Comment