使用 jQuery 删除动态列表中的最后一个输入字段

Remove last input field in dynamic list with jQuery

我如何设法从 "top" 按钮删除最后一个 <div><input type="text" name="mytext[]"></div>?当我创建许多字段时,当我单击 "remove glyphicon on top of them" 时,它会删除所有字段,而不是最后一个。

当我创建新字段时单击字段右侧的删除按钮时,它会删除该字段,但我也想从顶部按钮中删除

<div class="input_fields_wrap">
    <button class="add_field_button">
        <span class="glyphicon glyphicon-plus"></span>
    </button>
    <button class="remove_field" ><span class="glyphicon glyphicon-trash"></span>
    </button>
    <div><input type="text" name="mytext[]"></div>
</div>
$(document).ready(function () {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID
    var x = 1; //initlal text box count
    $(add_button).click(function (e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">\n\
                                <button ><span class="glyphicon glyphicon-trash"></button>\n\
                                </span></a></div>'); //add input box
        }
    });
    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});

要解决此问题,您可以使用 nextAll('div:last')。试试这个:

$wrapper.on("click", ".remove_field", function(e) { //user click on remove glyphicon
    e.preventDefault();
    $(this).nextAll('div:last').remove();
    x--;
})

Working example

请注意,我稍微修改了 JS,这样你就不会双重包装你的 jQuery 对象,我还稍微修改了 HTML 以便很明显哪个是 add/remove 按钮,即使不使用字形图标。

您应该找到该父项的最后一个子项并将其删除。

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon
  e.preventDefault();
  $(this).parent().children('div:last-child').remove();
  x--;
})