프로그래밍 언어/JQuery(제이쿼리)

Jquery 를 통한 동적 행 추가 및 삭제

낙산암 2023. 7. 21. 15:11
<html>
<head>
 
<title>동적 추가된 div태그에 이벤트 추가</title>
<style type="text/css">
.dynamicDiv {
    width:170px;
    background-color: #CBE7F4;
    text-align:center;
    font-weight:bold;
    padding: 3px 3px;
    cursor:pointer;
    margin:5px;
    border-radius:.25em;
    border:1px solid #449999;
}
</style>
<script language="javascript">
 
$(document).on('click', '.dynamicDiv', function() {
  console.log("동적 추가된 div태그 '"+$(this).attr("id")+"'이 클릭되었습니다.");
});
 
var index = 0;
var addDiv = function() {
  $("body").append("<div class='dynamicDiv' id='"+index+"'>동적추가 div " + index + "</div>");
  index++;
};
 
</script>
 
</head>
<body>
<input type="button" onclick="addDiv()" value="Div 태그 추가">
</body>
</html>

<!DOCTYPE html>
<html>    
    <head>        
    <meta charset="UTF-8">        
    <title>Add More Elements</title>        
    <script src="jquery-1.7.1.min.js"></script>        
    <script>            
        $(document).ready (function () {                
            $('.btnAdd').click (function () {                                        
                $('.buttons').append (                        
                    '<input type="text" name="txt"> <input type="button" class="btnRemove" value="Remove"><br>'                    
                ); // end append                            
                $('.btnRemove').on('click', function () {
                    $(this).prev().remove (); // remove the textbox
                    $(this).next ().remove (); // remove the <br>
                    $(this).remove (); // remove the button
                });
            }); // end click                                            
        }); // end ready        
    </script>    
    </head>    
    <body>        
        <div class="buttons">            
        <input type="text" name="txt"> <input type="button" class="btnAdd" value="Add"><br>        
        </div>    
    </body>
</html>