jquery 實現前端select標籤多級聯動
阿新 • • 發佈:2018-11-02
前端程式碼
function loadData(type,pid) { $.getJSON('BookTypeList.ashx', { type: type, pid: pid }, function (data) { //向服務期端傳遞引數,type ,標籤名後面的變數值, pid: 主鍵ID var typelist = $('#type' + type); typelist.empty(); if (data.length <= 0) { //如果沒有查到資料就插入一個無資料的選項 typelist.append('<option value="-1">無子分類</option>') } else { //遍歷伺服器端傳回的json資料 $.each(data, function (index, item) { //向select 標籤中新增資料 typelist.append('<option value="' + item.TypeId + '">' + item.TypeTitle + '</option>'); }); //這裡實現遞迴操作多級向select標籤中新增資料 if (type < 3) { loadData(type + 1, typelist.val()); } } }); }
呼叫該函式
$(function () { //首先載入一級分類的資料 loadData(1, 0); //載入二級分類 $('#type1').change(function () { loadData(2, $(this).val()); }); //載入三級分類 $('#type2').change(function () { loadData(3, $(this).val()); }); //如果有多級分類的話可以繼續載入 });
<body>
<select id="type1" name="type1"></select>
<select id="type2" name="type2"></select>
<select id="type3" name="type3"></select>
</body>
後臺伺服器程式碼 用c#實現
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.Script.Serialization; namespace Maticsoft.Web.Admin { /// <summary> /// BookTypeList1 的摘要說明 /// </summary> public class BookTypeList1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; Maticsoft.BLL.BookType booktypeBll = new BLL.BookType(); int type = int.Parse(context.Request["type"]); int pid = int.Parse(context.Request["pid"]); string where = ""; if (type == 1) { where = " TypeParentId=0"; } else { where = " TypeParentId=" + pid+" "; } DataTable dt = booktypeBll.GetList(where).Tables[0]; List<Maticsoft.Model.BookType> listType = new List<Model.BookType>(); foreach (DataRow dr in dt.Rows) { listType.Add(new Maticsoft.Model.BookType() { TypeId=Convert.ToInt32(dr["TypeId"]), TypeTitle=dr["TypeTitle"].ToString() }); } JavaScriptSerializer js = new JavaScriptSerializer(); context.Response.Write(js.Serialize(listType)); } public bool IsReusable { get { return false; } } } }
資料表結構必須是省市聯動,自連結表的型別才可以實現此功能