【发布时间】:2015-06-08 00:39:48
【问题描述】:
我有一个表单,我希望能够添加和删除文本框和标签。每个文本框前面都有一个标签,因此该标签是兄弟。我正在尝试仅选择文本框的同级,因此在删除文本框时也将其删除。 我的问题是如何选择以前的标签。删除文本框很简单,它是我作为参数传递给函数的最后一个文本框(因为我重新使用它)。删除文本框工作正常,只是前面的标签是一个挑战。这是我的功能。
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 代码的 sn-p 以获得清晰的图片
<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>
【问题讨论】:
-
小提琴也不错:),去这里jsfiddle.net
-
@Sam 正在使用 asp.net mvc,我已更新问题以仅包含相关 Razor 代码的 sn-p。
标签: javascript jquery asp.net-mvc razor asp.net-mvc-5