工作上有個需求是做樹狀的層級聯動,於是動手寫了一個可無限擴展的級聯下拉選單。程式碼寫得比較隨性,先記錄下來,之後有空再細細整理。

分類資料表主要包含以下欄位:
第一層下拉選單直接由後端輸出,並綁定 onChange 事件觸發後續載入:
<div id="select">
<select name="category_1" id="category_1" onChange="change('category_1');">
<option>請選擇分類</option>
<!-- {foreach from=$galleryCategory item=category} -->
<option value="{$category.id}">{$category.category_name}</option>
<!-- {/foreach} -->
</select>
</div>
對應取得頂層分類的 PHP 程式碼:
$sql = "select * from yl_gallery_category where pid = 0";
$galleryCategory = $db->query($sql);
$smarty->assign("galleryCategory", $galleryCategory);
關鍵在於 change() 函數:先判斷選中的值是否為合法正整數,若不是則清掉多餘的後續選單;若合法,就透過 AJAX 抓取下級分類並動態 append 一個新的 select,同時把過時的選項移除。
function change(val) {
var str = val; // select 的 id
var num; // 目前級數
var id; // 分類 id
num = str.substr(9, 10);
var nownum = parseInt(num) + 1; // 轉為數字並加一
id = $("#" + str).val();
var r = /^[1-9]+[0-9]*]*$/; // 正整數
if (!r.test(id)) {
$("select").each(function(index){
if (index + 1 > num) { $(this).remove(); }
});
return false;
}
var url = 'gallery.php?act=category&pid=' + id;
$.ajax({
type: "POST",
cache: false,
url: url,
datatype: 'json',
timeout: 3000,
success: function(result){
if (result != 0) {
var html = "<select name=category_" + nownum + " id=category_" + nownum + " onChange=change('category_" + nownum + "'); >";
html += "<option>請選擇分類 </option>";
var datas = eval(result);
$.each(datas, function(i, val){
html += "<option value='" + val.id + "' >" + val.category_name + "</option>";
});
html += "</select>";
$("select").each(function(index){
if (index + 1 > num) { $(this).remove(); }
});
$("#select").append(html);
} else {
$("select").each(function(index){
if (index + 1 > num) { $(this).remove(); }
});
}
},
error: false
});
}
後端依傳入的 pid 撈出子分類,若無資料則回傳 0,最後以 JSON 格式輸出:
$sql = "select * from yl_gallery_category where pid = " . $pid;
$res = $db->query($sql);
if (empty($res)) {
$res = 0;
}
echo json_encode($res);
如此一來,一層選完自動帶出下一層,就能實現不限層級的聯動效果了。