如何删除最后添加的输入框

时间:2013-05-24 10:49:32

标签: jquery html

我有一个问题,删除我追加的最后一个框,这里是我走了多远,我会感激我能得到的任何帮助。感谢。

$('#btn').on('click', function () {
            var num = parseInt($('#num').val(), 10);
            if (!isNaN(num)) {
                  var $div = $('#div');
                for(var i=0;i< num;i++) {
                     $div.append('<input id="toremove" type="text" name="subject" class="form_element" placeholder="e.g Biology, Economics, Geography, Commerce, Agric.Sci" /> <a href"#" id="remove" class="delete"><a/>')   ;
                }
            }
        });

        $('#remove').on('click', function() {
            $('#toremove').lastChild().remove();
        });

2 个答案:

答案 0 :(得分:3)

使用:(不要使用重复的ID ...而是使用类

$('#toremove:last').remove();

您可以将其更改为 -

$div.append('<input class="toremove"...

$('#div .toremove:last').remove();

答案 1 :(得分:1)

在此处使用:last Selector

$('#remove').on('click', function () {
    $('#div input:text:last').remove();
});

此外,您可以这样做,因为您已经使用 form_element 类作为输入:

$('#remove').on('click', function () {
    $('#div .form_element:last').remove();
});