SeouliteLab

이벤트 위임을 위한 jQuery .delegate() 메소드 본문

프로그래밍

이벤트 위임을 위한 jQuery .delegate() 메소드

Seoulite Lab 2024. 4. 2. 08:28

jQuery의 .delegate() 메소드는 이벤트 위임을 구현하는 데 사용됩니다. 이벤트 위임은 하위 요소에 대한 이벤트 처리를 상위 요소에 위임하여 효율적인 이벤트 처리를 가능하게 합니다.


예제 1: 버튼 클릭 이벤트 위임

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .delegate() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#container').delegate('button', 'click', function(){
        alert('버튼이 클릭되었습니다!');
      });
    });
  </script>
</head>
<body>

<div id="container">
  <button>버튼 1</button>
  <button>버튼 2</button>
  <button>버튼 3</button>
</div>

</body>
</html>

결과:

  • 버튼을 클릭하면 "버튼이 클릭되었습니다!"라는 경고창이 표시됩니다.

설명:
이 예제에서는 .delegate() 메소드를 사용하여 container ID를 가진 상위 요소에 버튼 클릭 이벤트를 위임합니다. 버튼을 클릭하면 해당 버튼의 이벤트가 처리되며, 모든 버튼에 대해 하나의 이벤트 핸들러만 사용됩니다.


예제 2: 마우스 오버 이벤트 위임

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .delegate() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#container').delegate('div', 'mouseover', function(){
        $(this).css('background-color', 'lightblue');
      });
      $('#container').delegate('div', 'mouseout', function(){
        $(this).css('background-color', '');
      });
    });
  </script>
  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: lightgray;
      margin: 10px;
    }
  </style>
</head>
<body>

<div id="container">
  <div class="box">박스 1</div>
  <div class="box">박스 2</div>
  <div class="box">박스 3</div>
</div>

</body>
</html>

결과:

  • 박스에 마우스를 올리면 배경색이 연보라색으로 변경되고, 마우스를 박스에서 벗어나면 원래대로 돌아갑니다.

설명:
이 예제에서는 .delegate() 메소드를 사용하여 container ID를 가진 상위 요소에 박스의 마우스 오버와 마우스 아웃 이벤트를 위임합니다. 박스에 마우스를 올리면 배경색이 변경되며, 마우스를 박스에서 벗어나면 배경색이 원래대로 돌아갑니다.


예제 3: 동적으로 요소 추가

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .delegate() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#container').delegate('button', 'click', function(){
        $('#container').append('<button>새로운 버튼</button>');
      });
    });
  </script>
</head>
<body>

<div id="container">
  <button>버튼 1</button>
</div>

</body>
</html>

결과:

  • 버튼을 클릭하면 새로운 버튼이 동적으로 추가됩니다.

설명:
이 예제에서는 .delegate() 메소드를 사용하여 container ID를 가진 상위 요소에 버튼 클릭 이벤트를 위임합니다. 버튼을 클릭하면 새로운 버튼이 동적으로 추가되며, 추가된 버튼도 클릭 이벤트가 발생합니다.


예제 4: 요소 삭제

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .delegate() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#container').delegate('span', 'click', function(){
        $(this).remove();
      });
    });
  </script>
</head>
<body>

<div id="container">
  <span>요소 1</span>
  <span>요소 2</span>
  <span>요소 3</span>
</div>

</body>
</html>

결과:

  • 요소를 클릭하면 해당 요소가 삭제됩니다.

설명:
이 예제에서는 .delegate() 메소드를 사용하여 container ID를 가진 상위 요소에 스팬 요소의 클릭 이벤트를 위임합니다. 스팬을 클릭하면 해당 스팬이 삭제됩니다.


예제 5: 폼 제출 이벤트 위임

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .delegate() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('#container').delegate('form', 'submit', function(e){
        e.preventDefault();
        alert('폼이 제출되었습니다!');
      });
    });
  </script>
</head>
<body>

<div id="container">
  <form>
    <input type="text">
    <button type="submit">제출</button>
  </form>
</div>

</body>
</html>

결과:

  • 폼을 제출하면 "폼이 제출되었습니다!" 라는 경고창이 표시됩니다.

설명:
이 예제에서는

.delegate() 메소드를 사용하여 container ID를 가진 상위 요소에 폼의 제출 이벤트를 위임합니다. 폼을 제출하면 경고창이 표시되며, 기본 제출 동작은 방지됩니다.


jQuery의 .delegate() 메소드를 사용하면 웹 페이지에서 이벤트 위임을 구현할 수 있습니다. 이를 통해 동적으로 생성되는 요소에 대한 이벤트 처리를 간편하게 할 수 있습니다.