태그를 동적으로 생성한 후 - append, html 등 ..
<style>
#parent{
width : 100px;
height : 100px;
border : 1px solid black;
}
</style>
<body>
<div id = "parent"></div>
<script>
$("#parent").click(function(){ // append 이벤트
$("#parent").append("<button id ='child' value='1234'>버튼</button>");
});
$("#child").click(function(){ // 동적으로 생성된 button
alert($(this).attr("value"));
});
</script>
</body>
동적으로 추가된 태그에는 이벤트가 동작하지 않는다!!.
$("#child").click(function(){}
은 이미 렌더링 되어서 동작하지 않는 것이다.
페이지가 로드 될 때
Script - $("#child").click(function(){}
은 있는데
html의 태그- #child
가 없어서 (append 하기 전에)
$(document).on("click", "#child", function(){ // on 이벤트로 변경
alert($(this).attr("value"));
});
위와 같이 on 을 사용하여 해결 할 수 있다.
on - 이벤트를 실행할 때 그 실행하는 순간, 바로 그 자리에서 찾아 연결해주는 메서드
attr()를 활용해서 동적으로 생선된 태그의 속성값(value)을 가져 올 수 있다.