
点击表头删除表头所属列
问题描述:
如何实现点击表格表头后删除表头所属的那一列?
解决方案:
方法一:使用原生 javascript
- 为每个表头添加一个 onclick 事件处理程序。
- 在事件处理程序中,获取被点击表头的列索引(从 0 开始)。
- 使用 deletecolumn() 方法删除表格中具有该列索引的列。
示例代码:
<table>
<thead>
<tr>
<th onclick="deletecolumn(this)">列 1</th>
<th onclick="deletecolumn(this)">列 2</th>
<th onclick="deletecolumn(this)">列 3</th>
</tr>
</thead>
<tbody>
<!-- 表格数据 -->
</tbody>
</table>
<script>
function deletecolumn(th) {
// 获取列索引
const index = th.cellindex;
// 删除列
th.parentelement.deletecell(index);
}
</script>
登录后复制
方法二:使用 jquery
- 为每个表头添加一个 click 事件监听器。
- 在事件处理程序中,使用 jquery 的 index() 方法获取被点击表头的列索引。
- 使用 jquery 的 remove() 方法删除表格中具有该列索引的列。
示例代码:
<table>
<thead>
<tr>
<th class="delete-column">列 1</th>
<th class="delete-column">列 2</th>
<th class="delete-column">列 3</th>
</tr>
</thead>
<tbody>
<!-- 表格数据 -->
</tbody>
</table>
<script>
$(function() {
$('.delete-column').click(function() {
// 获取列索引
const index = $(this).index();
// 删除列
$(this).parent().siblings('td:nth-child(' + (index + 1) + ')').remove();
$(this).remove();
});
});
</script>
登录后复制
以上就是如何通过点击表格表头删除整列数据?的详细内容,更多请关注米云其它相关文章!
