원문 출처 : http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click





Is there any difference between $('#whatever').on('click', function() and $('#whatever').click(function() ?




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. 

(on을 click 보다 좋아하는 이유는 메모리를 덜먹고 동적으로 생성되는 요소들이 잘 작동하기 때문임)

Consider the following html: (아래 코드좀 살펴보자)

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via ( 아래 코드로 새로운 버튼을 만들어 보자)

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that. ( Alert! 가 뜰것이다. on이나 click이나 다 쓸수 있다.)


클릭을 쓸때 When we use click

$("button.alert").click(function() {
    alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.
1. 많은 요소들은 많은 개별 핸들러를 필요로 해서 메모리 사용량이 증가됨.
2. 돌적으로 추가된 요소들은 기존의 핸들러들이 안 먹힘. 예를들어. 위의 html에서 새롭게 추가된 Alert!버튼은 rebind 해주지 않는 이상 동작 안함.

온을 쓸때 When we use .on

$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

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:

만약 .on("click", handler) 로 추가하면 .off("click", handler) 로 보통 없앨수 있다. 참조할 함수가 있다면 확실히 작동한다. 근데 없다면?? 네임스페이스를 써라.     

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via ( 아래 코드를 묶음 풀기)

$("#element").off("click.someNamespace");
share|improve this answer


+ Recent posts