用戶輸入昵稱與評論,點擊「評論」按鈕,不刷新頁面直接將新評論追加到表格列表頂部/底部,模擬早期「無刷新」體驗(實為純前端 DOM 操作,無後端交互)。
function AppendComment() {
var nicknameValue = document.getElementById("nickName").value;
var commentValue = document.getElementById("comment").value;
var tblComment = document.getElementById("tblComment");
var tr = tblComment.tBodies[0].insertRow(-1); // 插入新行
var tdNickName = tr.insertCell(-1);
tdNickName.innerHTML = nicknameValue;
var tdComment = tr.insertCell(-1);
tdComment.innerHTML = commentValue;
}
table.tBodies[0].insertRow(-1) 在 tbody 末尾插入行,tr.insertCell(-1) 插入單元格,自動處理 tbody 兼容性。input.value、textarea.value 獲取用戶輸入。innerHTML = userInput 極度危險,實際項目必須轉義或用 textContent。<table id="tblComment" border="1">
<tbody>
<tr><td>李莫:</td><td>非常好的網站</td></tr>
</tbody>
</table>
昵稱:<input type="text" id="nickName" /><br />
評論:<textarea id="comment"></textarea><br />
<input type="button" value="評論" onclick="AppendComment()" />
async function submitComment() {
const nickname = document.getElementById('nickName').value;
const content = document.getElementById('comment').value;
try {
const res = await fetch('/api/comments', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({nickname, content})
});
const comment = await res.json();
prependCommentToList(comment); // 前端渲染
document.getElementById('comment').value = '';
} catch (e) { alert('發布失敗'); }
}
function prependCommentToList(c) {
const tbody = document.querySelector('#tblComment tbody');
const tr = document.createElement('tr');
tr.innerHTML = `${escapeHtml(c.nickname)} ${escapeHtml(c.content)} `;
tbody.insertBefore(tr, tbody.firstChild);
}
function escapeHtml(str) {
return str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
關鍵:fetch 異步提交、後端返回新評論數據、前端安全渲染(轉義)、插入列表首位。