很多後台畫面都需要一張能直接編輯的表格。這份範例完全不依賴任何框架,只用原生 DOM API 就實作出新增、雙擊就地編輯、批次刪除、模糊查詢與顯示全部等功能,很適合拿來理解表格操作的底層原理。
程式用幾個全域變數記錄狀態:_OTable_ 指向表格本體、_oTbody_ 指向資料列容器、_arrSelect_ 存放被勾選要刪除的列索引,而 _oTempValue_ 則是編輯暫存區,用來備份修改前的原值,其中 $updateIndex 標記目前進入編輯狀態的列。
var _OTable_ = null;
var _oTbody_ = null;
var _arrSelect_ = new Array;
var _oTempValue_ = new Object;
_TempValue_["$updateIndex"] = -1;
var _TheadName_ = new Array("姓名","性別","年齡","籍貫","刪除否");
var CELLS_COUNT = _TheadName_.length - 1;
// 順手擴充 String,補上 trim
String.prototype.trim = function () {
return this.replace(/(^\s*)(\s*$)/g, '');
};
按下新增鈕時,若表格還不存在就先用 createElement 建出表頭與 tbody;接著用 insertRow(-1) 在最後補一列,insertCell(-1) 依序塞入四個欄位,最後一欄放勾選方塊。姓名欄做了非空檢查,避免產生空白列。
$oAdd.onclick = function () {
var _oCol1_ = document.getElementById("Col1");
var _oCol2_ = document.getElementById("Col2");
var _oCol3_ = document.getElementById("Col3");
var _oCol4_ = document.getElementById("Col4");
if (!_OTable_) { // 第一次新增時才建表
_OTable_ = document.createElement("table");
_OTable_.setAttribute("border", "1");
_OTable_.setAttribute("width", "800px");
var _Thead_ = _OTable_.createTHead();
var _TRow_ = _Thead_.insertRow(0);
for (var h = 0; h < CELLS_COUNT + 1; h++) {
_TRow_.insertCell(h).appendChild(document.createTextNode(_TheadName_[h]));
}
_oTbody_ = document.createElement("tbody");
_OTable_.appendChild(_oTbody_);
document.getElementById("TableData").appendChild(_OTable_);
}
if (!_oCol1_.value.trim()) { alert("姓名必須填寫!"); return; }
var _oRow_ = _oTbody_.insertRow(-1);
var _oCell1_ = _oRow_.insertCell(-1);
_oCell1_.appendChild(document.createTextNode(_oCol1_.value));
var _oCell2_ = _oRow_.insertCell(-1);
_oCell2_.appendChild(document.createTextNode(_oCol2_.value));
var _oCell3_ = _oRow_.insertCell(-1);
_oCell3_.appendChild(document.createTextNode(_oCol3_.value));
var _oCell4_ = _oRow_.insertCell(-1);
_oCell4_.appendChild(document.createTextNode(_oCol4_.value));
_oCol1_.value = ""; _oCol2_.value = ""; _oCol3_.value = ""; _oCol4_.value = "";
// 最後一欄:勾選方塊
var _oCell5_ = _oRow_.insertCell(4);
_oCell5_.setAttribute("style", "width:50px;");
var _oCheckBox_ = document.createElement("input");
_oCheckBox_.setAttribute("type", "checkbox");
_oCell5_.appendChild(_oCheckBox_);
_oCheckBox_.onclick = function () {
if (_oCheckBox_.checked) {
_arrSelect_.push(_oCheckBox_.parentNode.parentNode.rowIndex - 1);
}
};
_oRow_.ondblclick = editRow; // 雙擊進入編輯
};
進入編輯前,程式會先檢查「上一列是否還在編輯中」。若使用者改了內容,就跳出確認框詢問是否保存:選擇保存就把 input 的 value 寫回成文字節點,選擇放棄則用備份的 _oTempValue_ 還原。接著才把這一列的每個儲存格換成 <input type="text">,並把原值存進暫存物件。
_oRow_.ondblclick = function () {
var _oPreUpdateIndex_ = _oTempValue_["$updateIndex"];
var _oPreTempRow_ = null;
if (parseInt(_oPreUpdateIndex_) != -1) { // 先把上一列收尾
if (!_OTable_ || !_oTbody_) return;
_oPreTempRow_ = _oTbody_.rows[parseInt(_oPreUpdateIndex_)];
var _cancelornot_ = false;
for (var c = 0; c < CELLS_COUNT; c++) {
var node = _oPreTempRow_.cells[c].firstChild;
var val = document.all ? node.getAttribute("value") : node.value;
if (val != _oTempValue_["$" + c]) {
_cancelornot_ = confirm("你之前的內容作了修改,保存修改嗎?");
break;
}
}
if (_cancelornot_) {
var _firstNode_ = _oPreTempRow_.cells[0].firstChild;
var _firstVal_ = document.all ? _firstNode_.getAttribute("value") : _firstNode_.value;
if (!_firstVal_ || !_firstVal_.trim()) {
alert("姓名不能為空,請重新編輯!");
_firstNode_.focus();
return;
}
for (var c = 0; c < CELLS_COUNT; c++) {
var old = _oPreTempRow_.cells[c].firstChild;
var val = document.all ? old.getAttribute("value") : old.value;
_oPreTempRow_.cells[c].replaceChild(document.createTextNode(val), old);
delete _oTempValue_["$" + c];
}
} else {
for (var c = 0; c < CELLS_COUNT; c++) {
var old = _oPreTempRow_.cells[c].firstChild;
_oPreTempRow_.cells[c].replaceChild(
document.createTextNode(_oTempValue_["$" + c]), old);
delete _oTempValue_["$" + c];
}
}
}
_oTempValue_["$updateIndex"] = this.rowIndex - 1;
for (var c = 0; c < CELLS_COUNT; c++) {
var _textbox_ = document.createElement("input");
_textbox_.setAttribute("type", "text");
var _preNode_ = this.cells[c].firstChild;
_oTempValue_["$" + c] = _preNode_.nodeValue; // 備份原值
_textbox_.setAttribute("value", _preNode_.nodeValue);
this.cells[c].replaceChild(_textbox_, _preNode_);
}
};
刪除鈕會先把所有被勾選的姓名收集成一段提示文字,使用者確認後才「從後往前」刪除。之所以要倒著刪,是因為每刪一列後面索引都會往前挪,正序處理會漏刪。
$oDelete.onclick = function () {
if (_arrSelect_.length == 0) { alert("您還沒有選擇要刪除的行。"); return; }
if (_OTable_ && _oTbody_) {
var msg = "你確定要刪除名字是如下:\n";
for (var i = 0; i < _arrSelect_.length; i++) {
msg = msg.concat(
_oTbody_.rows[parseInt(_arrSelect_[i])].cells[0].firstChild.nodeValue + "\n");
}
msg = msg.concat("的信息嗎?");
if (!confirm(msg)) return;
for (var i = _arrSelect_.length - 1; i >= 0; i--) {
_oTbody_.deleteRow(parseInt(_arrSelect_[i]));
}
}
_arrSelect_.splice(0, _arrSelect_.length); // 清空選擇清單
};
更新鈕負責把仍在編輯中的那一列正式「定稿」:確認後逐格把 input 換回文字節點,並把 $updateIndex 重設為 -1。查詢鈕則會先處理未提交的編輯,再依下拉選單選定的欄位,用 RegExp 比對;比對失敗的列直接設為 display:none,查詢框留空時則全部顯示。
$oUpdate.onclick = function () {
var idx = _oTempValue_["$updateIndex"];
if (parseInt(idx) == -1) { alert("您未編輯任何更新行!"); return; }
if (_OTable_ && _oTbody_ && confirm("您確定修改嗎?")) {
var row = _oTbody_.rows[parseInt(idx)];
var nameNode = row.cells[0].firstChild;
var nameVal = document.all ? nameNode.getAttribute("value") : nameNode.value;
if (!nameVal || !nameVal.trim()) {
alert("姓名不能為空,請重新編輯!"); nameNode.focus(); return;
}
for (var c = 0; c < CELLS_COUNT; c++) {
var node = row.cells[c].firstChild;
var val = document.all ? node.getAttribute("value") : node.value;
row.cells[c].replaceChild(document.createTextNode(val), node);
delete _oTempValue_["$" + c];
}
}
_oTempValue_["$updateIndex"] = -1;
};
// 查詢核心:以正規表達式做不分大小寫比對
var _$oSelect_ = document.getElementById("selectCol");
var colIndex = parseInt(_$oSelect_.value);
var keyword = document.getElementById("Col9").value.trim();
var rows = _oTbody_.rows;
for (var r = 0; r < rows.length; r++) {
var row = rows[r];
if (!keyword) {
row.style.display = document.all ? "block" : "table-row";
} else {
var pat = new RegExp(keyword, "i");
if (!pat.test(row.cells[colIndex].firstChild.nodeValue.trim())) {
row.style.display = "none";
}
}
}
_arrSelect_.splice(0, _arrSelect_.length);
<fieldset> <legend>操作 Table 之增刪查改</legend> <fieldset> <legend>添加</legend> <label for="Col1">姓名:</label><input type="text" id="Col1" /> <label for="Col2">性別:</label><input type="text" id="Col2" /> <label for="Col3">年齡:</label><input type="text" id="Col3" /> <label for="Col4">籍貫:</label><input type="text" id="Col4" /> <input type="button" value="添加" id="btnAdd" /> </fieldset> <fieldset> <legend>查找</legend> <label for="Col9">查找內容:</label> <select name="selectCol" id="selectCol"> <option value="0" selected>姓名</option> <option value="1">性別</option> <option value="2">年齡</option> <option value="3">籍貫</option> </select> <input type="text" id="Col9" /> <input type="button" value="查找" id="btnFind" /> </fieldset> </fieldset> <fieldset id="TableData"><legend>表格數據</legend></fieldset> <input type="button" value="刪除" id="btnDelete" /> <input type="button" value="更新" id="btnUpdate" /> <input type="button" value="顯示全部" id="btnSelectAll" />
第一,insertRow(-1) 與 insertCell(-1) 傳 -1 代表「插在最後」,比自己算索引安全得多。第二,批次刪除一定要倒序。第三,這份程式大量使用 document.all 做瀏覽器判斷,那是 IE 時代的寫法,在今日專案中應改用標準 API;若要在正式環境使用,建議以 Vue、React 等框架以狀態驅動的方式重寫,會乾淨許多。