1

我如何设法<div><input type="text" name="mytext[]"></div>从“顶部”按钮中删除最后一个以进行删除?当我创建许多字段时,当我单击“删除它们顶部的字形图标”时,它会删除所有字段,而不是最后一个。

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

<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--;
    })
});
4

2 回答 2

2

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

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

工作示例

请注意,我稍微修改了 JS,这样您就不会对 jQuery 对象进行双重包装,并且我还稍微修改了 HTML,以便即使不使用字形图标,也可以很明显地看到添加/删除按钮。

于 2016-08-02T09:19:26.427 回答
0

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

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon
  e.preventDefault();
  $(this).parent().children('div:last-child').remove();
  x--;
})
于 2016-08-02T09:30:56.607 回答