三級聯動小案例

此小案例適合數據較少的相似三級聯動的小效果,省市區三級聯動參見 http://www.javashuo.com/article/p-vjddbmbj-g.htmlhtml

	<body>
		<select name="" id="prov">
			<option value="">請選擇省</option>
		</select>
		<select name="" id="city">
			<option value="">請選擇市</option>
			<option value="">請先選擇省</option>
		</select>
		<select name="" id="county">
			<option value="">請選擇縣</option>
			<option value="">請先選擇市</option>
		</select>
	</body>
</html>
<script src="jquery-1.8.1.min.js"></script>
<script>
	var provArr = ["遼寧","山西","河北"];
	//              0      1     2
	var cityArr = [["瀋陽","大連","鐵嶺"],["大同","太原"],["邯鄲","石家莊","唐山","雄安"]];
	//                 0    1     2       0       1        0      1       2       3     
	var countyArr = [[["s1","s2"],["d1"],["昌圖","蓮花鄉"]],[["t1","t2"],["y1"]],[["h1"],["s1","s2"],["tangshan1"],["xiongan1"]]];
	//                00            01       02              10          11      20        21
	//頁面加載後 將省的數組信息 添加到頁面上
	for(var i = 0; i < provArr.length; i++){
		$("#prov").append($("<option value="+i+">"+provArr[i]+"</option>"));
	}
	$("#prov").change(function(){//點擊省把市添加進來
		$("#city")[0].length = 1;
		var index = $(this).val();//省的下標  0-1
		var cityAry = cityArr[index];
		for(var i = 0; i < cityAry.length; i++){
			$("#city").append($("<option value="+index+"-"+i+">"+cityAry[i]+"</option>"));
		}
	})
	$("#city").change(function(){
		$("#county")[0].length = 1;
		var index = $(this).val();//0-0  0-1  0-2
		var proIndex = index.split("-")[0];//省的下標
		var cityIndex = index.split("-")[1];//城市的下標
		var countyAry = countyArr[proIndex][cityIndex];
		for(var i = 0; i < countyAry.length; i++){
			$("#county").append($("<option>"+countyAry[i]+"</option>"));	
		}
	})
</script>
相關文章
相關標籤/搜索