如何使用jQuery或原生JavaScript向HTML表格中添加行和列
解决方案
前置修正
你现有表格的DOM结构存在语法错误,<tbody> 内的 <td> 没有被 <tr> 标签包裹,这是导致你之前操作失效的核心原因之一,先修正表格结构:
<tbody> <tr> <td>Code: </td> <td class="text-center">Name: </td> <td class="text-center">Address: </td> <td class="text-center">Phone: </td> <td class="text-center">Options: </td> </tr> </tbody>
1. 添加列
jQuery 实现
如果要在所有行的指定位置插入新列,比如在第2列(索引从0开始)后插入标题为Test的列:
// 给表头加th $('#QueryTable thead tr').find('th').eq(2).after('<th class="text-center">Test</th>'); // 给所有内容行加对应td $('#QueryTable tbody tr').each(function(){ $(this).find('td').eq(2).after('<td class="text-center">测试内容</td>'); });
如果要直接在末尾加列,更简单:
$('#QueryTable thead tr').append('<th class="text-center">Test</th>'); $('#QueryTable tbody tr').append('<td class="text-center">测试内容</td>');
原生JS实现
const table = document.getElementById('QueryTable'); // 加表头 const headerRow = table.tHead.rows[0]; const newTh = document.createElement('th'); newTh.className = 'text-center'; newTh.textContent = 'Test'; headerRow.appendChild(newTh); // 加内容列 for(let i=0; i<table.tBodies[0].rows.length; i++){ const newTd = document.createElement('td'); newTd.className = 'text-center'; newTd.textContent = '测试内容'; table.tBodies[0].rows[i].appendChild(newTd); }
2. 添加行
jQuery实现
const newRow = ` <tr> <td>新的编码</td> <td class="text-center">新的名称</td> <td class="text-center">新的地址</td> <td class="text-center">新的电话</td> <td class="text-center">操作按钮</td> </tr> `; // 追加到tbody末尾 $('#QueryTable tbody').append(newRow);
原生JS实现
const tbody = document.getElementById('QueryTable').tBodies[0]; const newRow = tbody.insertRow(); // 插入新行,默认在末尾 // 插入单元格 const cell1 = newRow.insertCell(0); cell1.textContent = '新的编码'; const cell2 = newRow.insertCell(1); cell2.className = 'text-center'; cell2.textContent = '新的名称'; const cell3 = newRow.insertCell(2); cell3.className = 'text-center'; cell3.textContent = '新的地址'; const cell4 = newRow.insertCell(3); cell4.className = 'text-center'; cell4.textContent = '新的电话'; const cell5 = newRow.insertCell(4); cell5.className = 'text-center'; cell5.textContent = '操作按钮';
你之前代码失效的其他原因
- 没有区分表头和内容行的单元格标签,表头用
<th>,内容行应该用<td>,语义更规范 - 你只操作了
tr下的th,但tbody内的内容行没有th只有td,所以匹配不到节点导致插入失败
内容的提问来源于stack exchange,提问作者Gabriel Augusto
相关产品推荐
相关产品推荐

