Skip to content

jQuery Dynamic Event Binding #

Find similar titles

3회 업데이트 됨.

Edit
  • 최초 작성자
    jmchoi
  • 최근 업데이트
    hmkim

Structured data

Category
Programming

이벤트 바인딩이란? #

target의 addEventListener() 메서드는 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정한다. 일반적으로 Element, Document, Window지만 XMLHttpRequest와 같이 이벤트를 지원하는 모든 객체를 대상으로 지정할 수 있다.


동적 이벤트 바인딩(Dynamic Event Binding)이란? #

스크립트로 요소에 이벤트를 바인딩할 때 순서는 document > script 순서로 진행되기 때문에 일반적으로 document에 작성된 element에만 이벤트가 바인딩된다. 이후에 같은 요소를 추가할 때 추가한 요소에는 이벤트가 걸리지 않는다. 요소를 추가할 때마다 이벤트를 바인딩하면 코드가 복잡해지므로 jQuery를 이용해 쉽게 동적으로 이벤트 바인딩이 가능하다.


사용예시 #

<body>
    <div class="container">
      <div class="alert-wrap">
        <button class="btn-alert">알림</button>
      </div>
      <button class="btn-add-element">요소 추가</button>
    </div>
</body>
<script>
    var btnAddElement = $('.btn-add-element');
    btnAddElement.on('click', function () {
      var alertWrap = $('.alert-wrap');
      var newBtnAlert = '<button class="btn-alert">NEW 알림</button>';
      alertWrap.append(newBtnAlert);
    });
</script>

동적 바인딩 안 될 때 #

<script>
    var btnAlert = $('.btn-alert');
    btnAlert.on('click', function () {
      alert('Hello World!');
    });
</script>

Image

동적 바인딩 될 때 #

<script>
    var btnAlert = $('.btn-alert');
    $(document).on('click', '.btn-alert', function () {
      alert('Hello World!');
    });
</script>

Image

Reference #

0.0.1_20230725_7_v68