Javascript 无法删除包含单元格的列
我无法删除包含所有单元格的列。如果我尝试删除最后一列,效果很好,但如果我尝试在最后一列之前删除该列,则效果不理想 这是我的HTML的外观:Javascript 无法删除包含单元格的列,javascript,jquery,html-table,Javascript,Jquery,Html Table,我无法删除包含所有单元格的列。如果我尝试删除最后一列,效果很好,但如果我尝试在最后一列之前删除该列,则效果不理想 这是我的HTML的外观: <table id="tblData"> <thead> <tr style="background-color:green" id="trMain"> <th>Fixed 1</th>
<table id="tblData">
<thead>
<tr style="background-color:green" id="trMain">
<th>Fixed 1</th>
<th>Fixed 2</th>
<th>Fixed 3</th>
<th id="Collection1">Collection 1</th>
<th id="Collection2">Collection 2</th>
</tr>
<tr style="background-color:red" id="trSub">
<th>E1</th>
<th>E2</th>
<th>E3</th>
<th>
<table>
<thead>
<tr>
<th>P1</th>
<th>P2</th>
<th>P3</th>
</tr>
</thead>
</table>
</th>
<th>
<table>
<thead>
<tr>
<th>P1</th>
<th>P2</th>
<th>P3</th>
</tr>
</thead>
</table>
</th>
</tr>
</thead>
</table>
<button type="button" id="btnGet">Delete a Column</button>
$(document).ready(function () {
var colToDelete = 'Collection2';
$('#btnGet').click(function(){
var column = $("#tblData").find('#' + colToDelete);
var row = column.parent('tr').children();
var idx = row.index(column);
alert(idx)
$("#trMain").find("th:eq(" + idx + ")").remove();
alert(idx)
$("#trSub").find("th:eq(" + idx + ")").remove();
});
});
这是JS提琴:我已经更新了你的脚本,应该可以了
$(document).ready(function () {
var colToDelete = 'del1';
$('#btnGet').click(function(){
var column = $("#tblData").find('#' + colToDelete);
var row = column.parent('tr').children();
var idx = row.index(column);
$("#trMain").find("th:eq(" + idx + ")").remove();
$("#trSub > th:eq(" + idx + ")").remove();
});
});
您遇到了问题,因为您将一个表放在一个表中,所以两行的列不对应。您的第二行应该是这样的:
<tr style="background-color:red" id="trSub">
<th>E1</th>
<th>E2</th>
<th>E3</th>
<th>P1 P2 P3</th>
<th>P1 P2 P3</th>
</tr>
这是可行的:我之所以将P1 P2 P3放在单独的表中,是因为我希望它们作为列。它们是集合中的3个不同列。就像《黑客帝国》。
$('#btnGet').click(function(){
$("#trMain th").last().remove();
$("#trSub th").last().remove();
});