我无法得到正确的逻辑,这就是我的尝试:
<div class="container">
<div class="row">
<div class="col">
<button id="addTd" type="button" class="btn btn-danger">
Add Column
</button>
<button id="addTr" type="button" class="btn btn-danger">
Add Row
</button>
<table id="table-data" class="table table-bordered">
<thead>
<tr>
<td></td>
<td data-td-index="1"><input type="text" autofocus placeholder="Label" name="Name" ><button type="button" class="btn btn-primary removeColumn">-</button></td>
<td data-td-index="2"><input type="text" autofocus placeholder="Label" name="Name" ><button type="button" class="btn btn-primary removeColumn">-</button></td>
<td data-td-index="3"><input type="text" autofocus placeholder="Label" name="Name" ><button type="button" class="btn btn-primary removeColumn">-</button></td>
<td data-td-index="4"><input type="text" autofocus placeholder="Label" name="Name" ><button type="button" class="btn btn-primary removeColumn">-</button></td>
</tr>
</thead>
<tbody>
<tr class="tr_clone" data-row-index="1">
<td><button type="button" class="btn btn-primary removeRow">-</button></td>
<td><input type="text" autofocus placeholder="data" name="who" ></td>
<td><input type="text" autofocus placeholder="data" name="location" ></td>
<td><input type="text" placeholder="data" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="data" name="datepicker_end" class="datepicker"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
然后我执行以下操作来添加行和列并删除行
$("#addTr").on('click', function() {
var i = 0;
var $tr = $('tbody tr[data-row-index="1"]');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);
$("tbody tr").each(function(){
i++;
$(this).attr("data-row-index", i);
});
});
$("#addTd").on("click", function(){
$("thead tr").append('<td><input type="text" autofocus placeholder="Label" name="Name" ><button type="button" class="btn btn-primary removeColumn">-</button></td>');
$("tbody tr").append('</td> <td><input type="text" placeholder="data" name="datepicker_end" class="datepicker"></td>');
var i = 0;
$(document).find("thead td").each(function(){
i++;
$(this).attr("data-td-index", i);
});
});
$(document).on("click", ".removeRow", function(){
$(this).parent().parent().remove();
});
$(document).on("click", ".removeColumn", function(){
$(this).parent().parent().remove();
});
但是我无法理解如何删除列,我已经设法删除了一行。
一起玩答案 0 :(得分:2)
您可以获取按钮单击发生的单元格的索引,并删除具有相同索引的表格中的所有单元格。
e.g。
$(document).on("click", ".removeColumn", function(){
var index = $(this).parent().index() + 1;
$(this).closest("table").find("td:nth-child(" + index + ")").remove();
});
答案 1 :(得分:0)
也许按列号?
var colnum = $(e.target).closest("td").length;
$(e.target).closest("table").find("tr").each(function(){
$(this).find("td:eq(" + colnum + ")").remove()});