본문 바로가기
Frontend/jQuery

[jQuery] 동적으로 추가한 요소에 이벤트 걸기 (event binding)

by 지구 2018. 7. 10.

jQuery 동적 메소드를 통해서 DOM 객체에 추가했는데, 그 추가한 요소에 클릭이벤트를 걸으려니 계속 안됐다.

  • .after()
  • .html()
  • .append()
  • .prepend() 등..

 

처음엔 jQuery Selector 를 잘못잡은건가 싶었지만 찾아보니 그게 아니었고,

동적으로 추가한 요소는 마우스 액션이 등록되어있지 않기 때문에 마우스 이벤트를 걸어도 아무 반응이 없었던거였다..

 

그래서 찾은 해결방법. 당황하지 말고 아래의 'to-be' 로 적용하면 된다 :)

// as-is
$("#boardContent").on("click", function() {
	console.log( $(this).attr("id"); ); //-> not working
});


// to-be
$(document).on("click", "#boardContent", function() {
	console.log( $(this).attr("id"); ); //-> it working
});

 

 

반응형

댓글