JQUERY检索并删除以前的兄弟姐妹

JQUERY Retrieve and Remove Previous Sibling

本文关键字:兄弟姐妹 删除 检索 JQUERY      更新时间:2023-09-26

我有一个表单,希望能够添加和删除文本框和标签。每个文本框前面都有一个标签,因此该标签是同级标签。我试着只选择文本框的同级,这样当删除文本框时我也会删除它我的问题是如何选择上一个标签。删除文本框很简单,它是我将名称作为参数传递到函数中的最后一个文本框(因为我重复使用了它)。删除文本框效果很好,只是前面的标签是一个挑战。这是我的功能。

function remove(someName) {
 var count = $('input[name=' + someName + ']').length;
 if (count > 1) {
     $('input[name=' + someName + ']:last').remove();
     $(this).closest('label.numbers').remove();
     /*
     I have tried this one below but it doesn't work
     $('label.numbers > input[name=' + someName + ']:last').parent().remove();
     This too doesn't work.
     $('label.numbers > input[name=' + someName + ']:last').offsetParent().remove();
     */
 }

更新这是我的Razor代码片段,用于清晰的图片

            <div class="form-group">
            @Html.LabelFor(model => model.SupportingDocumentation, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div>
                    <label class="numbers"> 1 </label>
                    @Html.TextBoxFor(model => model.SupportingDocumentation, new { @class = "SupportingDocumentation" })
                    <input type="button" value="+" class="roundButton" onclick="add('SupportingDocumentation', 'SupportingDocumentation')" />
                    <input type="button" value="-" class="roundButton" onclick="removeElement('SupportingDocumentation')" />
                </div>
                <div> 
                    <label class="numbers"> 2 </label>
                    @Html.TextBoxFor(model => model.SupportingDocumentation, new { @class = "SupportingDocumentation" }) 
                </div>
                <div> 
                    <label class="numbers"> 3 </label>
                    @Html.TextBoxFor(model => model.SupportingDocumentation, new { @class = "SupportingDocumentation" }) 
                </div>
                @Html.ValidationMessageFor(model => model.SupportingDocumentation, "", new { @class = "text-danger" })
            </div>
        </div>

在您的代码中,当您尝试使用其引用来选择标签时,文本框已经被删除,而不是-

a) 你可以像这样一个接一个地删除它们-

var txtbox = $('input[name=' + someName + ']:last');
var lbl = txtbox.parent().find('label.numbers');
txtbox.remove();
lbl.remove();

b) 或者简单地删除父div,它将删除其中的所有内容-

var div = $('input[name=' + someName + ']:last').parent();
div.remove();

c) 或者将div中的html设为空-

var div = $('input[name=' + someName + ']:last').parent();
div.html('');

编辑

使用解决方案(a)-为您的案例提供一个示例

http://jsfiddle.net/15morm22/3/

正如Sam所指出的,我试图删除一个兄弟姐妹,而不是父姐妹。这是对我有用的jquery代码,这一切都要归功于Sam的努力。

$("#removeBtn").on("click", function(){
    var textbox = $('input[name=' + 'ThisElement' + ']:last').parent();
    var label = textbox.prev();
    textbox.remove();
    label.remove();
    return false;
});

这里是jsfiddle片段的链接