這個插件在靈活性上做了不少考量,提供了幾個關鍵配置以便在各類環境下使用,源碼完全開放,歡迎大家採用。開發它的起因,是前陣子維護一個四級聯動下拉框時,被其中 200 行程式碼、複雜結構與各種 bug 搞得頭疼(之所以這麼多行,是因為該下拉框有時只出現兩三層)。想來這類需求其實很常見,而 jQuery 生態裡又缺乏合適的現成插件,索性自己動手做一個。
源碼本身並不複雜,稍微棘手的是第二個插件使用了快取機制,理解起來略有門檻,後面會加以說明。
插件一:適合在不與伺服器進行 AJAX 互動的情境使用,需事先將所有下拉框資料一次讀出。
插件二:適用於每個子級下拉框都需 post 到伺服器取資料並綁定的情境。其優秀之處在於會把已用過的資料快取起來以達到高效率。特別注意:快取的鍵值並非僅是父下拉框的值,而是「從頂級下拉框到當前父下拉框」的值組合,這是為了應對相同父值卻對應不同子級的情況。基於同樣原因,postback 回傳給伺服器的表單中也會包含所有上層下拉框的值。
/*
* 級聯下拉框 jQuery 插件,V1.2
* Copyright 2011, Leo.Liu
* 插件一:cascadeDropDownData 在不與伺服器 AJAX 互動時使用,需預先讀出所有下拉框資料
* 方法二示範:分別為各下拉框綁定資料並指定 parentID
*/
jQuery.extend({
cascadeDropDownData: function () {
//配置屬性
this.removeFirst = true; //是否移除第一個項
this.appentAllValue = ''; //當父項目值等於此值時顯示所有項
this.sourceID = ''; //此下拉框ID
this.parentID = ''; //父下拉框ID
this.items = []; //項的資料,二維陣列 [['文本','值','父ID'],......]
this.selectValue = ''; //初始化選中的項
this.parentValue = null; //用於從一堆資料中篩選該組所需的項
//系統變量
this.child = null;
var currentDrop = null;
this.bind = function () {
currentDrop = $('#' + this.sourceID);
this.clear();
this.fillItem();
if (this.selectValue) { currentDrop.val(this.selectValue); }
this.setChange();
};
this.clear = function () {
if (this.removeFirst) {
currentDrop.empty();
} else {
for (var i = currentDrop[0].options.length - 1; i > 0; i--) {
currentDrop[0].options[i] = null;
}
}
};
this.fillItem = function () {
var _parentValue = this.parentValue;
if (this.parentID) _parentValue = $('#' + this.parentID).val();
var all = false;
if (this.appentAllValue && _parentValue == this.appentAllValue) all = true;
$.each(this.items, function (index, item) {
var val = item.length > 1 ? item[1] : item[0];
if (all || item.length <= 2 || item[2] == _parentValue) {
currentDrop.append('<option value="' + val + '">' + item[0] + '</option>');
}
});
};
this.setChange = function () {
if (this.parentID) $('#' + this.parentID).bind('change', this.change);
};
var _this = this;
this.change = function () {
_this.clear();
_this.fillItem();
currentDrop.change();
};
},
cascadeDropDownBind: {
bind: function (data, setting) {
var obj = new $.cascadeDropDownData();
$.extend(obj, setting);
obj.items = data;
obj.bind();
if (setting.child) {
setting.child.parentID = setting.sourceID
this.bind(data, setting.child);
}
}
}
});
該插件以鏈表結構管理各級下拉框,並透過 childItem 做快取;getRightOnChangeObj 會回溯到根節點,再依當前各層選定值找出正確的物件。使用時先以 bindTopDrop 綁定第一級,再以 bindCallback 逐級綁定子級並提供取資料的 URL:
var firstItems = null;
$.ajaxDropDownBind.bindTopDrop('Select1', firstItems, null, false, 'Select2');
$.ajaxDropDownBind.bindCallback('Select2', null, false, 'Select3', 'https://localhost:4167/GetDropDownData.ashx?action=select1');
$.ajaxDropDownBind.bindCallback('Select3', null, false, null, 'https://localhost:4167/GetDropDownData.ashx?action=select2');
$('#Select1').change();
最關鍵的一點是:級聯的 ID 設定不能缺席。完整的插件二原始碼較長,這裡聚焦於快取與鏈表的核心概念——每個下拉框物件都持有 parentObj 與 childItem,變更時先取得當前正確物件,若快取中已有對應子級資料就直接复用,否則新建實例、發請求並寫入快取。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>無限極級聯下拉框的封裝</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>無限極級聯下拉框的封裝</h1>
<select id="selCase"><option value="1">第一種方法</option>
<option value="2">第二種方法</option></select>
<input type="button" onclick="test()" value="綁定" />
<div id="selContainer"></div>
<script type="text/javascript" src="/Scripts/Jquery.cascadeDropDown-1.2.js"></script>
<script type="text/javascript">
function testcase1() {
var dataItem = [['a001','a001','0'], ['a002','a002','0'], ['a003','a003','0']
, ['b001','b001','a001'], ['b002','b002','a001'], ['b003','b003','a002']
, ['c001','001','b001'], ['c002','002','b001'], ['c003','003','b002']];
$.cascadeDropDownBind.bind(dataItem,
{ sourceID: 'Select1', selectValue: 'a001', parentValue: '0', removeFirst: false,
child: { sourceID: 'Select2', selectValue: 'b002',
child: { sourceID: 'Select3', selectValue: 'c002' } }
});
}
</script>
</div>
</form>
</body>
</html>
由於插件二需要伺服器端配合,這裡就不附上其測試程式碼。使用方法在註解中已有說明,歡迎大家踴躍交流指教。