下午好,我希望有人可以帮助我。
我对 jQuery
还很陌生,所以如果这是我犯的一个非常明显的错误,请原谅我。
我有一个表单,可以让我添加其他字段,我可以使用它,并且我已经得到了它,因此它们具有唯一的 ID 标签,但当我单击我的 removeFieldTeam
时,我希望如此> 它删除了我点击的特定字段。
目前,它会自动从底部向上删除字段。
感谢任何帮助。
最佳答案
这是更新后的 jquery 代码。我测试过,有效:
$(document).ready(function () {
// Set the counter value
var countTeam = 1;
$("#addFieldTeam").click(function () {
event.preventDefault();
// If there's more than 10 fields, throw an alert
if (countTeam == 10) {
alert("Only 10 fields allowed");
return false;
}
// Declaring our new div and adding the form input.
var newField = $(document.createElement('div'))
.attr({
id: "newFieldTeam" + countTeam,
class: "form-group"
});
newField.after().html(
'<label class="form-label-bold" for="fieldTeam' + countTeam + '"' + '>' +
'Team '+countTeam+'</label>' +
'<input class="form-control fullish" id="fieldTeam' + countTeam +
'" type="text">' +
'<span><a class="minuslinkreport removeFieldTeam" href="#"> - </a></span>'
);
// adding the new field to the page within the #fieldGroupTeam div
newField.appendTo('#fieldGroupTeam');
// Increase the counter by 1
countTeam++;
console.log(countTeam);
});
// Once there's no more fields to delete, throw an error.
$(document).on('click', ".removeFieldTeam", function () {
event.preventDefault();
if (countTeam < 2) {
alert("No fields to remove");
return false;
}
countTeam--
console.log(countTeam);
// Decrease the counter by 1 and remove the field.
console.log($(this).closest('div'));
$(this).closest('div').remove();
});
});
对于删除按钮,我将其从 id 更改为 class,并且 onclick 我正在删除最接近的 div。
请测试并告诉我这是否有效。
这是工作 fiddle
关于javascript - jQuery 从动态生成的字段中删除特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48077197/