且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery动态添加/删除HTML元素

更新时间:2023-09-02 09:57:58

演示

html

demo

html

<form id="myForm">
    <div style="margin-bottom:4px;" class="clonedInput">
        <input type="button" class="btnDel" value="Delete" disabled="disabled" />
        <input type="text" name="input1" />
    </div>

    <div>
        <input type="button" id="btnAdd" value="add another name" />
    </div>
</form>​

jQuery

$(document).ready(function() {

    var inputs = 1; 

    $('#btnAdd').click(function() {
        $('.btnDel:disabled').removeAttr('disabled');
        var c = $('.clonedInput:first').clone(true);
            c.children(':text').attr('name','input'+ (++inputs) );
        $('.clonedInput:last').after(c);
    });

    $('.btnDel').click(function() {
        if (confirm('continue delete?')) {
            --inputs;
            $(this).closest('.clonedInput').remove();
            $('.btnDel').attr('disabled',($('.clonedInput').length  < 2));
        }
    });


});

资源