본문 바로가기

[ programing ]/JavaScript + JQuery

jQuery on() 동적으로 추가된 엘리먼트 이벤트 발생시키기


  • on() 메서드


[box 추가 ] 버튼을 클릭하면 동적으로 box엘리먼트가 추가 됩니다.

기존의 box 엘리먼트의 이벤트는 잘 동작하지만 동적으로 추가된 box엘리먼트에는 이벤트가 동작하지 않습니다. 

이것은 bind() 메서드는 동적으로 생성된 엘리먼트를 찾지 못하기 때문입니다.

on() 메서드로 수정하여 동적으로 추가된 엘리먼트의 이벤트가 동작하도록 수정합니다.




<style>

html * { margin:0; padding:0;  }

#wrapper { margin-left:300px; }

#nav > input { margin-left:300px; }

.box { width:150px; height:150px; border:2px solid blue;}

.box.over { background-color: red; }

.box.out { background-color: green; }

.box.down { background-color: blue; }

.box.up { background-color: pink; }

.box.click { background-color: brown; }

.box > p { padding:30px; color:white; }

#nav { margin:20px; }

</style>

<script>

$(document).ready(function(){

var box = $('.box'); // 엘리먼트를 동적으로 생성


$('#wrapper').on({  // bind()메서드 대신 on()메서드 사용

mouseover:function(){

var tg = $(this);

tg.removeClass().addClass('box over');  //.box.over { background-colorred; }

tg.find('> p').text('mouseover');

},

mouseout:function(){

var tg = $(this);

tg.removeClass().addClass('box out'); // .box.out { background-colorgreen; }

tg.find('> p').text('mouseout');

},

click:function(){

var tg = $(this);

tg.removeClass().addClass('box click'); // .box.click { background-colorbrown; }

tg.find('> p').text('click');

}

}, '.box'); // 메서드 인자 체크

$('#nav > :input').bind('click', function(){

$('#wrapper').append(box.eq(0).clone()); // 클릭하면 #wrapper'의 자식생성

console.log($('#wrapper').html());

           console.log("----------------------------------");


});

});

</script>

</head>

<body>

<div id="nav">

<input type="button" value="box추가" />

</div>

<div id="wrapper">

<div class="box out"> 

<p>'나는 박스란다'</p>


</div> 

</div>

</body>