純前端也能做出一個具備新增、刪除、修改、模糊查詢的表格小系統。這個範例的複雜度不在個別功能,而在「編輯狀態如何管理」——同一時間只允許一列處於編輯中,切換時要處理未提交修改的去留。
var _OTable_ = null; // 表格物件
var _oTbody_ = null; // tbody
var _arrSelect_ = new Array; // 已勾選要刪除的列索引
var _oTempValue_ = new Object; // 暫存編輯中的原值
_TempValue_["$updateIndex"] = -1; // -1 代表目前沒有列在編輯
var _TheadName_ = new Array("姓名", "性別", "年齡", "籍貫", "刪除否");
var CELLS_COUNT = _TheadName_.length - 1;
String.prototype.trim = function () { return this.replace(/(^\s*)(\s*$)/g, ''); };
$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);
[_oCol1_, _oCol2_, _oCol3_, _oCol4_].forEach(function (col) {
_oRow_.insertCell(-1).appendChild(document.createTextNode(col.value));
col.value = "";
});
// 最後一列放勾選框
var _oCell5_ = _oRow_.insertCell(4);
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);
};
};
這是整份程式最精彩的部分。雙擊某列時,把每個儲存格的文字節點換成 input,同時把原值記到 _oTempValue_;若上一列還在編輯中,先比對現值與原值,判斷使用者是否改動過,再決定提示儲存或直接還原。
_oRow_.ondblclick = function () {
var _oPreUpdateIndex_ = _oTempValue_["$updateIndex"];
if (parseInt(_oPreUpdateIndex_) != -1) { // 有列正在編輯,先收尾
var _oPreTempRow_ = _oTbody_.rows[parseInt(_oPreUpdateIndex_)];
var changed = false;
for (var c = 0; c < CELLS_COUNT; c++) {
var node = _oPreTempRow_.cells[c].firstChild;
var data = document.all ? node.getAttribute("value") : node.value;
if (data != _oTempValue_["$" + c]) { changed = true; break; }
}
if (changed) {
if (!confirm("你之前的內容作了修改,保存修改嗎?")) {
// 不保存:還原成原值
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];
}
} else {
// 保存:把 input 的 value 固化成文字節點
var first = _oPreTempRow_.cells[0].firstChild;
var firstVal = document.all ? first.getAttribute("value") : first.value;
if (!firstVal || !firstVal.trim()) {
alert("姓名不能為空,請重新編輯!"); first.focus(); return;
}
for (var c = 0; c < CELLS_COUNT; c++) {
var n = _oPreTempRow_.cells[c].firstChild;
var v = document.all ? n.getAttribute("value") : n.value;
_oPreTempRow_.cells[c].replaceChild(document.createTextNode(v), n);
delete _oTempValue_["$" + c];
}
}
}
}
// 把這一列轉為可編輯
_oTempValue_["$updateIndex"] = this.rowIndex - 1;
for (var c = 0; c < CELLS_COUNT; c++) {
var box = document.createElement("input");
box.setAttribute("type", "text");
var pre = this.cells[c].firstChild;
_oTempValue_["$" + c] = pre.nodeValue; // 記錄原值
box.setAttribute("value", pre.nodeValue);
this.cells[c].replaceChild(box, pre);
}
};
$oDelete.onclick = function () {
if (_arrSelect_.length == 0) { alert("您還沒有選擇要刪除的行."); return; }
if (_OTable_ && _oTbody_) {
var msg = "你確定要刪除名字是如下:\n";
for (var i = 0; i < _arrSelect_.length; i++) {
msg += _oTbody_.rows[parseInt(_arrSelect_[i])].cells[0].firstChild.nodeValue + "\n";
}
msg += "的信息嗎?";
if (!confirm(msg)) return;
for (var i = _arrSelect_.length - 1; i >= 0; i--) {
_oTbody_.deleteRow(parseInt(_arrSelect_[i])); // 由後往前刪,避免索引位移
}
}
_arrSelect_.splice(0, _arrSelect_.length); // 清空選擇列表
};
$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 n = row.cells[c].firstChild;
var v = document.all ? n.getAttribute("value") : n.value;
row.cells[c].replaceChild(document.createTextNode(v), n);
delete _oTempValue_["$" + c];
}
}
_oTempValue_["$updateIndex"] = -1;
};
查詢的做法是逐列比對,不中 THEN 就把該列的 style.display 設為 none。這裡有個跨瀏覽器的小陷阱:IE 下要設 "block",其他瀏覽器則需 "table-row",否則表格列會恢復成錯誤的顯示模式。
var $pat = new RegExp(_$olike_.value.trim(), "i"); // i 表示忽略大小寫
for (var r = 0; r < _$rowcollection_.length; r++) {
var row = _$rowcollection_[r];
if (!_$olike_.value.trim()) {
row.style.display = document.all ? "block" : "table-row"; // 空白則全部顯示
} else if (!$pat.test(row.cells[colIndex].firstChild.nodeValue.trim())) {
row.style.display = "none";
}
}
// 查詢後記得重置所有 checkbox,並清空刪除列表
// 「顯示全部」按鈕則把每列的 display 都設回 block / table-row
整份程式有幾個值得學的設計:以 $updateIndex 明確標記「目前哪列在編輯」,把狀態集中管理;用「比對原值」判斷使用者是否真的改過,避免無意義的確認框;批次刪除時從索引大的往小的刪,防止刪一筆就位移的問題。另外原始碼大量使用 document.all 與 getAttribute("value") 來讀取 input 的值,這在當年是為了相容 IE,現在一律寫成 input.value 即可,程式會乾淨許多。