jQuery on() 메서드
예시
<p> 요소에 클릭 이벤트를 연결합니다.
$("p").on("click", function(){
alert("The paragraph was clicked.");
});
정의 및 사용
on() 메서드는 선택한 요소와 자식 요소에 대한 하나 이상의 이벤트 핸들러를 연결합니다.
jQuery 버전 1.7부터 on() 메서드는 bind(), live() 및 delegate() 메서드를 대체합니다. 이 방법은 API에 많은 일관성을 제공하며 jQuery 코드 기반을 단순화하므로 이 방법을 사용하는 것이 좋습니다.
참고: on() 메서드를 사용하여 첨부된 이벤트 핸들러는 현재 및 미래 요소(예: 스크립트로 생성된 새 요소) 모두에 대해 작동합니다.
팁: 이벤트 핸들러를 제거하려면 off() 메소드를 사용하십시오.
팁: 한 번만 실행되고 자체적으로 제거되는 이벤트를 첨부하려면 one() 메서드를 사용하십시오.
통사론
$(selector).on(event,childSelector,data,function,map)
Parameter | Description |
---|---|
event | Required. Specifies one or more event(s) or namespaces to attach to the selected elements. Multiple event values are separated by space. Must be a valid event |
childSelector | Optional. Specifies that the event handler should only be attached to the specified child elements (and not the selector itself, like the deprecated delegate() method). |
data | Optional. Specifies additional data to pass along to the function |
function | Required. Specifies the function to run when the event occurs |
map | Specifies an event map ({event:function, event:function, ...}) containing one or more event to attach to the selected elements, and functions to run when the events occur |
직접 해보십시오 - 예
연결 요소에 여러 이벤트를 연결하는 방법입니다.
를 사용하여 선택한 요소에 여러 이벤트 핸들러를 연결하는 방법입니다.
에 사용자 지정 네임스페이스 이벤트를 연결하는 방법입니다.
데이터를 전달하는 방법.
on() 메서드가 아직 생성되지 않은 요소에도 작동함을 보여줍니다.
제거 off() 메서드를 사용하여 이벤트 핸들러를 제거하는 방법.