jquery

click과 on의 차이

화이팅하자9 2023. 10. 22. 22:02

click과 on의 차이점

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.7.1.min.js"></script>
    <style>
        button{
            width: 100px;
            height: 60px;
            border: none;
            font-weight: 600;
            font-size: 1.5rem;
            margin: 5px;
        }
        .click{
            background-color: lightblue;
        }
        .on{
            background-color: lightsalmon;
        }
    </style>
</head>
<body>
    <button class="click">click</button>
    <button class="on">on</button>
    <br><br><br>

    <script>
        //동적 이벤트 바인딩
        //$(doument).on('이벤트타입','이벤트대상','이벤트핸들러')
        
        //click 버튼 클릭시 click메소드
        $('.click').click(()=>{
            console.log('click');
            $('body').append('<button class="click">click</button>')
        })

        //on 버튼 클릭시 on메소드 
        $(document).on('click','.on',()=>{
            console.log("on");
            $('body').append('<button class="on">on</button>')
        })

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

click은  눌렀을시에 consolebody에 추가가 되지만

body의 클래스에는 실행및  console이 적용이 안된다.

<-- 이유는 click는 최초의 선언된 요소에만 동작하기 때문

 

그러나

 

on은 눌렀을시 consolebody에 추가가 되면서

body에 있는 클래스에도 실행및 console이 적용이 된다.