代碼:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script type="text/javascript" src="../js/jquery-1.11.3.js" ></script> <style type="text/css"> body { font-size:15px; } div { width:400px; height:20px; border:1px solid #000000; background-color:#ddd; padding:10px; } </style> <script type="text/javascript"> $(function () { function Init(node) { return node.html("<option>---請選擇---</option>"); } //多維數組做數據來源 var db = { 廣東: { 珠海市: "珠海縣1,珠海縣2,珠海縣3", 深圳市: "深圳縣1,深圳,深圳縣3", 廣州市:"廣州縣1,廣州縣2,廣州縣3", }, 廣西: { 南寧市: "南寧縣1,南寧縣2,南寧縣3", 百色市: "百色縣1,百色縣2,百色縣3", 桂林市: "桂林縣1,桂林縣2,桂林縣3", }, 江西: { 市1: "縣1,縣2,縣3", 市2: "縣1,縣2,縣3", 市3: "縣1,縣2,縣3", } }; //初始化select節點 $.each(db, function (changShang) { $("#selF").append("<option>" + changShang + "</option>"); }) //一級變動 $("#selF").change(function () { //清空二三級 Init($("#selB")); Init($("#selC")); $.each(db,function (cs,pps) { if ($("#selF option:selected").text() == cs) { $.each(pps, function (pp, xhs) { $("#selB").append("<option>" + pp + "</option>"); }); $("#selB").change(function () { Init($("#selC")); $.each(pps, function (pp,xhs) { if ($("#selB option:selected").text()==pp) { $.each(xhs.split(','), function () { $("#selC").append("<option>" + this + "</option>"); }) } }) }) } }) }) }) </script> </head> <body> <h2>三級聯動:省、市、縣</h2> <div class="bg-primary"> 省:<select id="selF"> <option>--請選擇--</option> </select> 市:<select id="selB"> <option>--請選擇--</option> </select> 縣:<select id="selC"> <option>--請選擇--</option> </select> <p id="pid"></p> </div> </body> </html>
結果: