演示
html部分
<!DOCTYPE html>
<html>
<head>
<title>表格示例</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>更新时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- 这里是虚拟数据行,你可以根据需要添加更多 -->
<tr>
<td>2023-10-13 10:00 ---- PM</td>
<td>
<button onclick="moveUp(this)">上移</button>
<button onclick="moveDown(this)">下移</button>
<button onclick="moveToTop(this)">置顶</button>
<button onclick="moveToBottom(this)">置底</button>
<button onclick="removeRow(this)">删除</button>
</td>
</tr>
<tr>
<td>2023-10-13 02:30 ---- AM</td>
<td>
<button onclick="moveUp(this)">上移</button>
<button onclick="moveDown(this)">下移</button>
<button onclick="moveToTop(this)">置顶</button>
<button onclick="moveToBottom(this)">置底</button>
<button onclick="removeRow(this)">删除</button>
</td>
</tr>
</tbody>
</table>
<button onclick="addRow()">添加数据行</button>
<script>
//添加行
function addRow() {
var tableBody = document.getElementById("tableBody");
var newRow = document.createElement("tr");
newRow.innerHTML = `
<td>${getCurrentTime()+'----'+Math.round(Math.random()*100+1)}</td>
<td>
<button onclick="moveUp(this)">上移</button>
<button onclick="moveDown(this)">下移</button>
<button onclick="moveToTop(this)">置顶</button>
<button onclick="moveToBottom(this)">置底</button>
<button onclick="removeRow(this)">删除</button>
</td>
`;
tableBody.appendChild(newRow);
}
//移除行
function removeRow(button) {
var row = button.parentNode.parentNode;
row.remove();
}
function getCurrentTime() {
var now = new Date();
var year = now.getFullYear();
var month = (now.getMonth() + 1).toString().padStart(2, '0');
var day = now.getDate().toString().padStart(2, '0');
var hours = now.getHours().toString().padStart(2, '0');
var minutes = now.getMinutes().toString().padStart(2, '0');
var time = `${year}-${month}-${day} ${hours}:${minutes}`;
return time;
}
</script>
</body>
</html>
上移
function moveUp(button) {
var row = button.parentNode.parentNode;
if (row.previousElementSibling) {
console.log(" ~ file: tabel.html:67 ~ moveUp ~ row.previousElementSibling:", row.previousElementSibling)
row.parentNode.insertBefore(row, row.previousElementSibling);
}
}
下移
function moveDown(button) {
var row = button.parentNode.parentNode;
if (row.nextElementSibling) {
console.log(" ~ file: tabel.html:74 ~ moveDown ~ row.nextElementSibling:", row.nextElementSibling)
row.parentNode.insertBefore(row.nextElementSibling, row);
}
}
置顶
function moveToTop(button) {
var row = button.parentNode.parentNode;
var tableBody = row.parentNode;
tableBody.insertBefore(row, tableBody.firstElementChild);
}
置底
function moveToBottom(button) {
var row = button.parentNode.parentNode;
var tableBody = row.parentNode;
tableBody.appendChild(row);
}