gpt4 book ai didi

javascript - 通过动态添加删除行和列来调整 html 表格的大小?

转载 作者:行者123 更新时间:2023-11-28 12:34:46 24 4
gpt4 key购买 nike

我希望能够从 html 表格中添加删除行列(又称调整大小)

表格应该是矩形的,稍后它将代表一些二维数组值。

由于表格会刷新多次并且可能会变大,因此我认为清空并再次填充它不是一个好的解决方案。

我想调整我现在拥有的单元格的大小,并在处理新单元格之前清除以前编辑的单元格。

我的问题是调整大小,我可以通过迭代行并添加删除单元格,然后添加删除行来想到一些解决方案,但我问是否有一些现成的解决方案使用 js 或 jQuery 来完成这项工作或在至少添加删除列?

示例表 (5x3)

Sample Table (5x3)

<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>
</tbody>
</table>

最佳答案

这是一个例子。 Working jsFiddle here

我在表格下方添加了按钮来开始表演:

<input id="addcol" type="button" value="Add Column" />
<input id="remcol" type="button" value="Reomve Column" />
<input id="addrow" type="button" value="Add row" />
<input id="remrow" type="button" value="Remove row" />

jQuery/Javascript:

$(document).ready(function() {

$('#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);
var $newRow = $("<td>" + n + "</td>");
$("table.table-editor tr:eq(" + n + ")").append($newRow);
});
});

$('#remcol').click(function() {
var $tablerow = $('table.table-editor').find('tr');

$tablerow.each(function(index, value){
$("table.table-editor tr:eq("+index+") td:eq(-1)").remove();
});
});

$('#addrow').click(function() {
$('table.table-editor').append("<tr></tr>");
$('table.table-editor tr:eq(0) td').each(function(index, value){
$("table.table-editor tr:eq(-1)").append("<td>"+index+"</td>");
});
});

$('#remrow').click(function() {
$('table.table-editor tr:eq(-1)').remove();
});

}); //END $(document).ready()

Reference

关于javascript - 通过动态添加删除行和列来调整 html 表格的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345951/

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