아직 생성되지 않은 버튼(동적 엘레먼트)에 기능 부여하기

 

동적 바인딩 : parent를 대상으로 이벤트 로직 부여

 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>

    </head>
    <script>

        $(function(){

            //동적 바인딩 , parent를 대상으로 이벤트 로직 부여
            //$(".remove").on("click",function(){})

            $("#file_box").on("click",".removebtn",function(){
                $(this).parent().remove();
            })

            $("#plusbtn").on("click",function(){
                var line = $("<div></div>");
                line.append($("<input type=file>"));
                line.append($("<input type=button class=removebtn value=->"));
                $("#file_box").append(line);
            })
        })

    </script>
    <body>
        <input type="button" id="plusbtn" value="+">
        <div id="file_box">

        </div>
    </body>
</html>

 

            //동적 바인딩 , parent를 대상으로 이벤트 로직 부여
            //$(".remove").on("click",function(){})

            $("#file_box").on("click",".removebtn",function(){
                $(this).parent().remove();
            })

#file_box 안에 .removebtn 클래스를 클릭하면 작동

자신의 부모를 지운다.

+ Recent posts