.on 메소드 문법

반응형

동적으로 생성된 태그의 이벤트를 걸면 뜻대로 동작하지 않는다.

예를 들면

 

JSP

<script type="text/javascript">

$(document).ready(function(){
	
	$("#staticSB").change(function() {
	      alert(" 정적 변경 감지");
	   })
       
})

function appendTest(){
	
	var html = '';
	
	html += '<select id="staticSB">';
	html += '<option>dynamic1</option>';
	html += '<option>dynamic2</option>';
	html += '<option>dynamic3</option>';
	html += '<option>dynamic4</option>';
	html += '<option>dynamic5</option>';
	html += '</select>';
	
	$("#parent").empty();
	$("#parent").append(html);
	
}


</script>

</head>
<body>
<button type="button" onclick="appendTest()">append?</button>
<div id="parent">

</div>
</body>
</html>

View


이미 'staticSB'라는 id을 가진 selectBox에 change 메서드를 걸어놨지만,

동적으로 생성된 'staticSB'라는 id를 가진 selectBox가 아무런 동작도 하지 않는다.

 

원인


1. 처음 페이지가 로드될 때 (클라이언트가 페이지에 접속할 때)

2.

$("#staticSB").change(function() { alert(" 정적 변경 감지"); })

이 부분이 ready 함수 안에 있기 때문에 제일 먼저 실행하게 된다.

2.'staticSB'라는 id를 가진 태그를 찾는다. 

3.하지만 'staticSB'라는 id는 아직 존재하지 않기 때문에 찾지 못한다.

4. 결국 찾지 못한 JavaScript는 포기하고 이벤트를 연결하지 않는다.

 

 

해결


.on

.on : 간단하게 말해서 특정 이벤트를 실행할 때 그 실행하는 순간, 바로 그 자리에서 찾아 연결해주는 메서드


이벤트 바인딩 메서드 변화

 .bind() -> .live() -> .delegate() -> .on()

조건

jQuery 1.7 이상

문법

.on (events [, selector] [, data], handler)

 

문법 예시01

$(document).on('change','#staticSB',function(){
		alert(" 동적 변경 감지");
	}) 

문법 예시02

$("#staticP").on({ "click": function() { alert("click!"); },
		"mouseenter": function() { alert("mouseenter"); }, 
		"mouseleave": function() { alert("mouseleave"); }, 
		"copy": function() {alert("copy")},
		"cut": function() {alert("cut")}
		});

 

실전 예시

<script type="text/javascript">

$(document).ready(function(){

$(document).on('change','#staticSB',function(){
		alert(" 동적 변경 감지");
	}) 

})

function appendTest(){
	
	var html = '';
	
	html += '<select id="staticSB">';
	html += '<option>dynamic1</option>';
	html += '<option>dynamic2</option>';
	html += '<option>dynamic3</option>';
	html += '<option>dynamic4</option>';
	html += '<option>dynamic5</option>';
	html += '</select>';
	
	$("#parent").empty();
	$("#parent").append(html);
	
}


</script>

</head>
<body>
<button type="button" onclick="appendTest()">append?</button>
<div id="parent">

</div>
</body>
</html>

View

 

이렇게 잘 작동하는 것을 볼 수 있습니다.

 

.on 메소드엔 다양한 이벤트를 걸 수 있습니다.

 

[jQuery || JavaScript] HTML + jQuery Event 총 정리

Event jQuery 홈페이지에 .on 메소드를 보던 중 .on (events [, selector] [, data], handler) 이런 식으로 나와있었다. 여기서 말하는 events 칸엔 뭘 적는 걸까? 그렇다 바로 그것을 알아보겠습니다. (무조건 .o..

java119.tistory.com

 

반응형

+ Recent posts