删除动态块

时间:2015-02-25 20:38:13

标签: javascript jquery html

请帮我找错 此函数在div id = container

中添加新的动态div
function DynamicDiv() {
             var dynDiv = document.createElement("div");
             name_id++;
             dynDiv.id = 'div_' + name_id;
             dynDiv.innerHTML = name_id;
             dynDiv.style.width = "200px";
             dynDiv.style.height = "100px";
             dynDiv.style.left = "50px";
             dynDiv.style.top = "50px";
             dynDiv.className = "resize";

             document.getElementById('container').appendChild(dynDiv);



             $('.resize').draggable({
                 containment: "parent"
             })

             $(".resize").click(function () {
                 var id = this.id;
                 alert(id);
                 this.style.backgroundColor = 'green';

             });



         };

当你按下按钮删除当前块时我需要 我试过了

function del() {
             $(this).remove();

         }

但是这段代码不起作用,我认为问题在于div动态

感谢

1 个答案:

答案 0 :(得分:0)

如果我理解正确,下面应该可以解决问题



$(function() {

    var name_id = 0;
    
    function dynamicDiv() {
       
        var dynDiv = $('<div>')
                            .attr('id', name_id++)
                            .css({
                                'width': '200px',
                                'height': '100px',
                                'left': '50px',
                                'top': '50px'
                            })
                            .addClass('resize');
        
        $('#container').append(dynDiv);
    
        dynDiv.draggable({
            containment: 'parent'
        });
    
        dynDiv.click(function() {
            var id = $(this).attr('id');
            alert(id);
            $(this).css('background-color', 'green');
        });
        
    };

    function del() {
        $('.resize').last().remove();
    };

    $('#add').click(dynamicDiv);
    $('#delete').click(del);
    
});
&#13;
.resize {
    border: solid 1px black;
    background-color: blue;
    margin: 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="container"></div>
<input id="add" type="button" value="Add new" />
<input id="delete" type="button" value="Delete latest" />
&#13;
&#13;
&#13;