後台管理介面裡,表格的勾選功能幾乎是必備配備:全選、取消全選、單筆勾選時同步收集 ID。以下是常用的一套寫法,示範如何搭配 jQuery 與自訂的陣列輔助方法完成它。
// 判斷值是否在陣列中
Array.prototype.in_array = function(e){
for(i=0; i<this.length; i++){
if(this[i] == e) return true;
}
return false;
}
// 取得字串在陣列中的索引
Array.prototype.find_str = function(string){
var str = this.join("");
return str.indexOf(string);
}
補充一句:直接擴充 Array.prototype 在現代專案中並不建議,容易與其他函式庫或程式碼衝突,改用 Array.prototype.indexOf() 與 includes() 會更安全。
var houseIds = new Array();
// 全選/取消全選
$("#chebox-list-all").click(function(){
if($("#chebox-list-all").attr("checked")){
$("[name='checkboxes']").attr("checked", 'true'); // 全選,收集 id
var ids = document.getElementsByName('checkboxes');
var value = new Array();
for(var i = 0; i < ids.length; i++){
if(ids[i].checked) houseIds.push(ids[i].value);
}
alert(houseIds);
} else {
$("[name='checkboxes']").removeAttr("checked"); // 取消全選,清空 id
houseIds = [];
alert(houseIds);
}
});
// 單筆勾選:切換 id 的收錄狀態
function check(obj){
if(!houseIds.in_array(obj.value)){
houseIds.push(obj.value);
alert(houseIds);
} else {
var index = houseIds.find_str(obj.value);
houseIds.splice(index, 1)
alert(houseIds);
}
}
全選按鈕的處理分成兩支:勾上時把所有 name 為 checkboxes 的項目設為 checked,再逐一收集 value 塞進 houseIds;取消時則移除 checked 屬性並清空陣列。單筆勾選的 check() 函數透過 in_array() 判斷該值是否已在陣列中,若沒有就加入,若已有則找出位置並用 splice() 移除,達到切換效果。
這份程式碼有幾個地方值得優化。首先,收集勾選值其實不必手寫迴圈,用 $("[name='checkboxes']:checked").map(function(){ return this.value; }).get() 一行就能完成。其次,attr("checked") 在 jQuery 1.6 之後的語意已轉由 prop() 負責,判斷勾選狀態應改用 $(this).prop("checked") 或 this.checked。最後,find_str() 用 join("") 後比對索引的方式在值可能重疊時會出錯,改用 indexOf() 取得真正的陣列索引更可靠。