IT_susu

동적 HTML에 이벤트 처리하는 방법(시간 차를 두고 이벤트를 처리하는 방법) 본문

[ javascript ]/jQuery

동적 HTML에 이벤트 처리하는 방법(시간 차를 두고 이벤트를 처리하는 방법)

고베베 2018. 8. 5. 12:41

이벤트를 걸 당시에 해당 html이 아직 존재하지 않는다면 이벤트는 해당 html에 연결되지 않는다.

이는 마치 존재하지 않는 변수에 어떤 함수를 연결하는 것과 같은 행위다.


그러나 동적으로 html을 생성할 때는 처음부터 그 dom요소가 존재하지 않으므로 이벤트를 걸기가 애매해진다.

이럴 때는 2가지 방법이 있다.


1) 부모요소 혹은 body에 이벤트를 걸어놓는다.

$menu.on("click", "li", function(){
// li의 부모요소에 클릭 이벤트를 걸어 놓음
});



1번 방법으로 안될 경우에 함수로 맵핑하는 방법이 있다.


2) 함수로 맵핑하여 다른 메소드에서 호출한다.


- 함수 맵핑(이벤트 해지 후 재설정)

function RefreshSomeEventListener() {
    // Remove handler from existing elements
    $("#wrapper .specific-selector").off(); 

    // Re-add event handler for all matching elements
    $("#wrapper .specific-selector").on("click", function() {
        // Handle event.
    }
}


- 우선 ready이벤트에서 호출해 놓은 뒤,

$(document).ready(function() {
    // Other ready commands / code

    // Call our function to setup initial listening
    RefreshSomeEventListener();
});


- 동적으로 요소를 추가할 때마다 해당 메소드를 재설정

function SomeMethodThatAddsElement() {
    // Some code / AJAX / whatever.. Adding element dynamically

    // Refresh our listener, so the new element is taken into account
    RefreshSomeEventListener();
}


Comments