请引用我的 jsfiddle,我的 jquery 仅适用于我点击的第一个“X”,但不适用于第二个或第三个?
2) 当它只留下一个输入时如何禁用它?
<div class="main-form">
<fieldset id="ingt">
<legend></legend>
<div class="formheader">
<label style="width:170px;"></label>
<label></label>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][0][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][0][ingredient]" />
<span id="remove">X</span>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][1][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][1][ingredient]" />
<span id="remove">X</span>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][2][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][2][ingredient]" />
<span id="remove">X</span>
</div>
<div id="add"></div>
<button id="addi" type="button" onclick="add_field()">Add </button>
</fieldset>
</div>
$(function () {
$("#remove").click(function () {
$(this).parent().remove();
});
});
最佳答案
一个元素的ID必须是唯一的,用类代替
<span class="remove">X</span>
然后
$(function () {
$(".remove").click(function () {
$(this).parent().remove();
});
});
ID 选择器将仅返回具有所述元素的第一个元素,因此您的选择器 $("#remove")
将返回具有 id remove
的第一个元素因此点击处理程序将仅添加到该元素
此外,由于您有一个添加按钮,我假设您将添加动态元素,所以使用 event delegation处理新元素
$(function () {
//if you want to make the last item in the list(in terms of position) to non removable
$(".main-form").on('click', '.remove:not(:last)', function () {
$(this).parent().remove();
});
});
演示:Fiddle
或
$(function () {
$(".main-form").on('click', '.remove', function () {
//if you want to make the last item in the list to non removable
if ($('.remove').length > 1) {
$(this).parent().remove();
}
});
});
演示:Fiddle
关于javascript - jquery remove 只影响第一个跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20870144/