`HTMLTableElement.insertRow(index)` 可在表格中插入新列(`
<!DOCTYPE html>
<html>
<head>
<script>
function insRow() {
var table = document.getElementById('myTable');
var row = table.insertRow(0); // 插入到最頂端(索引 0)
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
<tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>
</table>
<br>
<input type="button" onclick="insRow()" value="Insert row">
</body>
</html>
function addRow(tableId, dataArray, position = -1) {
var table = document.getElementById(tableId);
if (!table) return null;
var row = table.insertRow(position);
dataArray.forEach(function(text, i) {
var cell = row.insertCell(i);
cell.innerHTML = text;
});
return row;
}
// 使用範例
addRow('myTable', ['A1', 'B1'], 0); // 頂端新增
addRow('myTable', ['A2', 'B2'], -1); // 底端新增
addRow('myTable', ['A3', 'B3'], 2); // 插入到第 3 列位置(索引 2)
function deleteRow(tableId, index) {
var table = document.getElementById(tableId);
if (table.rows[index]) table.deleteRow(index);
}
// 刪除第一列
deleteRow('myTable', 0);
// 刪除最後一列
deleteRow('myTable', -1);
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 8px; }
.actions button { margin-right: 4px; }
</style>
<table id="dataTable">
<thead><tr><th>Name</th><th>Age</th><th>Action</th></tr></thead>
<tbody></tbody>
</table>
<div class="actions">
<input id="name" placeholder="Name">
<input id="age" type="number" placeholder="Age">
<button onclick="addData()">新增</button>
</div>
<script>
function addData() {
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
if (!name || !age) return alert('請填寫完整');
var tbody = document.querySelector('#dataTable tbody');
var row = tbody.insertRow(-1);
row.insertCell(0).textContent = name;
row.insertCell(1).textContent = age;
var btnCell = row.insertCell(2);
btnCell.innerHTML = '';
document.getElementById('name').value = '';
document.getElementById('age').value = '';
}
</script>