对于另一种删除列的方法,允许您删除表中的任何列。
工作 jsFiddle 示例
HTML:
<h1>Add/Remove Column Example:</h1>
<span class="blurb">Instructions:<br/>1. Click Add Column button to append table to end.<br />2. Click <span class="remove">rem</span> to remove THAT column. <br />3. Code is currently set to COLORIZE rather than remove, just adjust in code and click RUN button at top left.</span><br/><br/>
<table class="table-editor" id="table1">
<colgroup class=""></colgroup>
<colgroup class=""></colgroup>
<colgroup class=""></colgroup>
<colgroup class=""></colgroup>
<colgroup class=""></colgroup>
<tbody>
<tr class="highlighted-row">
<td>•</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="normal-row">
<td></td>
<td>•</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="normal-row">
<td></td>
<td></td>
<td>•</td>
<td></td>
<td></td>
</tr>
<tr class="normal-row">
<td class='remove'>rem</td>
<td class='remove'>rem</td>
<td class='remove'>rem</td>
<td class='remove'>rem</td>
<td class='remove'>rem</td>
</tr>
</tbody>
</table>
<input id="addcol" type="button" value="Add Column" />
jQuery代码:
$('#addcol').click(function() {
var $tablerow = $('table.table-editor').find('tr');
count = 0;
$tablerow.each(function(index, value){
count += 1;
//alert('Working on row: ' + count);
var $listitem = $(this);
//alert('ListItem: ' + $listitem.index());
n = parseInt($listitem.index());
//alert('Value of n: ' + n);
if (n == 3) {
var $newRow = $("<td class='remove'>rem</td>");
$("table.table-editor tr:eq(" + n + ")").append($newRow);
}else{
var $newRow = $("<td>" + n + "</td>");
$("table.table-editor tr:eq(" + n + ")").append($newRow);
}
});
});
$(document).on('click', 'td.remove', function() {
var ndx = $(this).index() + 1;
//alert('Val of ndx: ' + ndx);
$('td:nth-child(' +ndx+ ')').css('background-color','red'); //comment this line to remove (see next line)
//$('td:nth-child(' +ndx+ ')').remove(); //UNCOMMENT this line to remove (see prev line)
});
参考:用jQuery
单行隐藏表格列
使用jQuery点击删除表格行