반응형

 

이벤트 연결 메소드1

 

 

아래와 같은 식으로 변화했으며,

현재는 on과 off를 사용한다.

 

이벤트 연결 이벤트 제거
$(selector).bind(…) $(selector).unbind(…)
$(selector).live(…) $(selector).die(…)
$(selector).delegate(…) $(selector).undelegate(…)
$(selector).on(…) $(selector).off(…)

 

 

 

on, one, off 사용법

 

 

$(selector).on(event, childSelector, data, function)
// 선택된 요소와 하위 요소에 한 개 이상의 이벤트를 바인딩
// 현재 로드 된 요소 및 스크립트로 생성될 새로운 요소에도 적용됨

$(selector).one(event, data, function)
// 선택된 요소와 하위 요소에 한 개 이상의 이벤트를 바인딩. 이벤트가 한번만 수행되고 제거됨

$(selector).off(event, selector, function(eventObj))
// 선택된 요소에 on메소드로 연결된 이벤트를 제거

 

 

 

  • 정적 요소 생성
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
.sttBg {
  background-color: black;
  color: white;
}
.dynmBg {
  background-color: hotpink;
  color: lime;
}
.fontGold {
  color: gold;
}
</style>
</head>
<body>
    <p>on(event[, selector][, data], fn) / one(event[,data], fn) / off(event[, selector][, fn]</p>
    <div></div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    // data {key:value} 형식으로 작성 후 ebent객체의 data속성으로 key에 접근하여 값을 얻음

    // 정적요소 대상 on()
    $('p').on('mouseover', {static:'정적요소bind방식'},function(e){
        $(this).toggleClass('sttBg');
        // console.log(e.data.static);
        $(this).text(e.data.static);
        
    });
</script>
</body>
</html>

 

결과 화면1 : 마우스를 가져다댈 시 text의 내용이 변경됨

 

 

 

  • 동적 요소 생성
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
.sttBg {
  background-color: black;
  color: white;
}
.dynmBg {
  background-color: hotpink;
  color: lime;
}
.fontGold {
  color: gold;
}
</style>
</head>
<body>
    <div></div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    // 동적 요소 생성
    let addP = $('<p>동적요소1</p><p>동적요소2</p>');
    $('div').append(addP);

    // 동적요소 대상 부모요소.on(event[,childSelector][,data],fn)
    // delegate방식 >> 정적요소 부모에게 이벤트를 주고 자식은 위임받는 형태
    // $(부모).on(이벤트, 이벤트의 적용대상인 자식요소, 함수);
    $('div').on('mouseover', 'p', {dynamic:'동적요소delegate방식'},function(e){
        $(this).toggleClass('dynmBg');
        $(this).text(e.data.dynamic);
    });
</script>
</body>
</html>

 

결과 화면2 : 마우스 가져갈시 변경됨

 

 

 

  • off : 이벤트 제거
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
.sttBg {
  background-color: black;
  color: white;
}
.dynmBg {
  background-color: hotpink;
  color: lime;
}
.fontGold {
  color: gold;
}
</style>
</head>
<body>
    <p>on(event[, selector][, data], fn) / one(event[,data], fn) / off(event[, selector][, fn]</p>
    <div></div>
    <button>일괄 제거(정적대상으로만)</button>
    <button>동적요소</button>
    <button>특정 이벤트 제거</button>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>

    // 정적요소 대상 on(event[,data],fn)
    $('p').on('mouseover', {static:'정적요소bind방식'},function(e){
        $(this).toggleClass('sttBg');
        $(this).text(e.data.static);
    });

    // 정적대상 이벤트2
    let rmv;
    $('p').on('mouseover', rmv = function(){
      $(this).toggleClass('fontGold');
    });

    // 동적 요소 생성
    let addP = $('<p>동적요소1</p><p id="pp">동적요소2</p>');
    $('div').append(addP);

    $('div').on('mouseover', 'p', {dynamic:'동적요소delegate방식'},function(e){
        $(this).toggleClass('dynmBg');
        $(this).text(e.data.dynamic);
    });

    $('div').on('mouseover', '#pp', function(){
      alert('접근시 알람');
    });

    $('button').eq(0).on('click', function(){ // 바인딩 - 정적요소 대상
      // 동적인 방식으로 만들어진 것은 제거되지 않음
      $('p').off('mouseover'); // p요소에 부여된 마우스 오버 이벤트 제거
    
      $('p').text('배경색 토글 이벤트가 제거되었음');
    });
      
    $('button').eq(1).on('click', function(){
      // 동적대상 이벤트 제거는 - 부모의 이벤트를 제거해야 함
      $('div').off('mouseover'); // 동적대상의 부모에게 부여된 이벤트를 제거
    });
      
    $('button').eq(2).on('click', function(){
      // 같은 이벤트 중 일부분의 처리만 제거
      $('p').off('mouseover', rmv);
      $('div').off('mouseover', '#pp');
    });
</script>
</body>
</html>

 

결과 화면3-1 : 일괄 제거 버튼 클릭 시 상단에 있는 정적 대상만 제거되고 다른 것은 변경됨

 

결과 화면3-2 : 동적요소 버튼 클릭 시 정적 요소만 변경됨

 

결과 화면3-3 : 특정 이벤트 제거 버튼 클릭 시 마지막 동적요소2에 있는 알람이 작동하지 않음

 

 

 

이벤트 연결 메소드 (bind) : 정적 대상 방식

 

버전이 업데이트 되면서 on으로 작동시킴

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    bind
    실행(로딩)전 document에 생성되어 있는 요소에만 이벤트 핸들러가 동작
    (*동적 요소에는 이벤트 핸들러(처리기)가 동작하지 않음) <br><br>

    <div class="wrapper">
        <input type="button" class="btn" value="정적버튼">
        <input type="button" id="clear" value="해제">

        <!-- 동적버튼이 위치할 지정 -->
    </div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    // 정적 대상 방식
    let bb = $('<input type="button" class="btn" value="bird 버튼">');
    $('.wrapper').append(bb);

    // bind(event, fn)
    $('.btn').on('click', function(){ // 정적대상 방식
        $('<input>',{
            type: 'button',
            class: 'btn',
            value: '새 버튼'
        }).appendTo('.wrapper');
    });

    $('#clear').click(function(){
        $('.btn').off('click');
    });

</script>
</body>
</html>

 

결과 화면4 : 정적버튼, bird 버튼 클릭 시 새 버튼 생성됨. 해제 버튼 클릭 시 버튼 다 적용 안 됨

 

 

=> 동적 버튼 확인 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    bind
    실행(로딩)전 document에 생성되어 있는 요소에만 이벤트 핸들러가 동작
    (*동적 요소에는 이벤트 핸들러(처리기)가 동작하지 않음) <br><br>

    <div class="wrapper">
        <input type="button" class="btn" value="정적버튼">
        <input type="button" id="clear" value="해제">

        <!-- 동적버튼이 위치할 지정 -->
    </div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    // 정적 대상 방식
    let bb = $('<input type="button" class="btn" value="bird 버튼">');
    $('.wrapper').append(bb);

    for(let i=0; i<3; i++) {
        let nb = $('<input type="button" class="btn" value="동적for버튼' + i + '">');
        $('.wrapper').append(nb);

        if(i == 1) {
            // bind(event, fn)
            $('.btn').on('click', function(){ // 정적대상 방식
                $('<input>',{
                    type: 'button',
                    class: 'btn',
                    value: '새 버튼'
                }).appendTo('.wrapper');
            });
        }
    }

    $('#clear').click(function(){
        $('.btn').off('click');
    });

</script>
</body>
</html>

 

결과 화면5 : 동적 for 버튼 2 클릭 제외 전부 새 버튼 생성됨

 

 

=> 동적for버튼0과 1의 경우 on인 것을 기준으로 미리 실행되기에 정적 버튼으로 취급한다.

 

 

 

이벤트 연결 메소드 (delegate) : 동적 대상 방식

 

버전이 업데이트 되면서 on으로 작동시킴

 

 

1. 동적 버튼 추가 및 해제

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    delegate(위임, 대리)
    부모의 이벤트를 물려받은 선택자에 적용되는 이벤트
    (* 부모요소는 반드시 정적대상이어야 함/ 부모를 특정하기 힘들 경우 최상단 document지정 가능)

    <div class="wrapper">
        <input type="button" class="btn" value="정적버튼">
        <input type="button" id="clear" value="해제">

        <!-- 동적버튼이 위치할 지정 -->
    </div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    // delegate(selector, event, fn) 에서 on 메소드로 변경됨
    // on(event, selector, fn)
    $('.wrapper').on('click', '.btn', function(){ // 동적대상 방식
        $('<input>',{
            type: 'button',
            class: 'btn',
            value: '새 버튼'
        }).appendTo('.wrapper');
    });

    $('#clear').on('click', function(){
        // 이벤트 부여대상의 이벤트 해제
        $('.wrapper').off('click');
    });
</script>
</body>
</html>

 

결과 화면6 : 정적버튼 클릭 시 추가됨

 

 

 

2. 파일 선택 영역 추가

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div>
        <input type="file">
        <button id="add">파일 선택 영역 추가</button>
    </div>

<script src="../js/jquery-3.7.1.min.js"></script>
<script>
    $('#add').click(function(){

        // 동적으로 생성됨
        let v_file = "<p>";
        v_file += "<input type='file'>";
        v_file += "<button class='del'>삭제</button>";
        v_file += "</p>";

        $('div').append(v_file);
    });

    // delegate방식으로 삭제버튼에 이벤트 주기
    // $(부모).on(event, selector, fn);
    $('div').on('click', '.del', function(){
        // class=del의 부모는 p이지만 동적요소이므로 부모자격이 없음
        // empty(대상요소만 지워줌와 remove(대상 요소와 자식까지 지워줌) 사용 가능
        console.log(this); // <button class='del'>삭제</button>"
        console.log( $(this).parent() ); // 부모 p 요소 포함하여 출력됨

        $(this).parent().remove();
    });

</script>
</body>
</html>

 

결과 화면7-1 : 파일 선택 영역 추가 버튼 클릭 시 하단에 추가로 늘어남

 

결과 화면7-2 : 삭제 버튼 클릭 화면

 

 

반응형