在按添加按钮之前,它已经显示一行,其中包含三个输入框和一个删除按钮,当我按添加
按钮时,它会添加一行,现在当我按添加按钮时,我有两行第二次
显示4行
,按第三次
后显示8行
我的代码:
<div class="row">
<div class="col-12">
<h3>Add Video</h3>
<form id="insertvideo" method="post">
<table id="addrow" width="100%">
<td><input type="button" class="btn btn-success addButton col-3 offset-1" value="add"/></td>
<tr class="clonetr">
<td>Video Title<input type="text" id="videotitle" name="videotitle[]" class="form-control"></td>
<td>Video description<input type="text" id="videodesc" name="videodesc[]" class="form-control"></td>
<td>Video Links<input type="text" id="videolink" name="videolink[]" class="form-control"></td>
<td><input type="button" class="btn btn-danger deleteButton" value="delete"/></td>
</tr>
</table>
</form>
</div>
</div>
<script>
$(function(){
$(".addButton").click(function(){
$('.clonetr').closest("tr").clone(true).appendTo("#addrow");
});
$(".deleteButton").click(function(){
$(this).closest("tr").remove();
});
});
</script>
我只想在按下添加
按钮后添加一行。
最佳答案
因为您每次都克隆所有现有的 tr
。只需克隆最后一个 tr
并附加它即可。
另一点是,当有多个 tr
时,您必须显示删除按钮。因为如果删除所有 tr,则无法使用 add
按钮进行克隆。
$(function(){
$(".addButton").click(function(){
$('.clonetr:last').clone(true).appendTo("#addrow");
});
$(".deleteButton").click(function(){
if($('.deleteButton').length > 1){
$(this).closest("tr").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-12">
<h3>Add Video</h3>
<form id="insertvideo" method="post">
<table id="addrow" width="100%">
<td><input type="button" class="btn btn-success addButton col-3 offset-1" value="add"/></td>
<tr class="clonetr">
<td>Video Title<input type="text" id="videotitle" name="videotitle[]" class="form-control"></td>
<td>Video description<input type="text" id="videodesc" name="videodesc[]" class="form-control"></td>
<td>Video Links<input type="text" id="videolink" name="videolink[]" class="form-control"></td>
<td><input type="button" class="btn btn-danger deleteButton" value="delete"/></td>
</tr>
</table>
</form>
</div>
</div>
关于javascript - 按添加按钮后我的行多次添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57906739/