gpt4 book ai didi

javascript - 如何删除表中的一列?

转载 作者:行者123 更新时间:2023-12-01 02:13:43 26 4
gpt4 key购买 nike

我无法得到正确的逻辑,这就是我尝试过的:

<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();
});

但是我无法理解如何删除列的逻辑,但我已经设法删除了行。

Here it is a jsFiddle一起玩

最佳答案

您可以获取按钮单击所在单元格的索引,并删除表格中具有相同索引的所有单元格。

例如

$(document).on("click", ".removeColumn", function(){
var index = $(this).parent().index() + 1;
$(this).closest("table").find("td:nth-child(" + index + ")").remove();
});

关于javascript - 如何删除表中的一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49589654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com