純js寫省市區三級聯動效果

效果圖:html

this

代碼: code

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>三級聯動</title>
	<style>
		* {
			margin: 0px;
			padding: 0px;
		}

	</style>
</head>

<body>
	省:<select name="" id="pre" style="width: 100px;" onchange="chg(this);">
		<option value="-1">請選擇</option>
	</select> 市:
	<select name="" id="city" style="width: 100px;" onchange="chg2(this);">
	</select> 區:
	<select name="" id="area" style="width: 100px;">
		
	</select>


	<script>
		var pres = ["北京 ", "上海 ", "山東 "];
		var cities = [
			["東城 ", "海淀 ", "朝陽 "],
			["浦東 ", "徐匯 ", "嘉定 "],
			["青島 ", "菏澤 ", "煙臺 "]
		];
		var area = [
			[
				["東城一 ", "東城二 ", "東城三 "],
				["海淀一 ", "海淀二 ", "海淀三 "],
				["朝陽一 ", "朝陽二 ", "朝陽三 "],
			],
			[
				["浦東一 ", "浦東二 ", "浦東三 "],
				["徐匯一 ", "徐匯二 ", "徐匯三 "],
				["嘉定一 ", "嘉定二 ", "嘉定三 "],
			],
			[
				["青島一 ", "青島二 ", "青島三"],
				["菏澤一 ", "菏澤二", "菏澤三"],
				["煙臺一 ", "煙臺二", "煙臺三"],
			],
		];
        
		var preEle = document.getElementById("pre");
		var cityEle = document.getElementById("city");
		var areaEle = document.getElementById("area");
        /*省份遍歷*/
		for (var i = 0; i < pres.length; i++) {
            /*給option添加值,value值,其中pres[i]爲值,i爲value值*/
			var op = new Option(pres[i], i);
			preEle.options.add(op);
		};
        
        /*點擊省份*/
		var val01;
		function chg(obj) {

			val01 = obj.value;

			var citiesval = cities[val01];
			var areaval = area[val01][0];
            /*清空市區*/
			cityEle.options.length = 0;
			areaEle.options.length = 0;
            /*遍歷市*/
			for (i = 0; i < citiesval.length; i++) {
				var op = new Option(citiesval[i], i);
				cityEle.options.add(op);
			}

            /*遍歷區*/
			for (i = 0; i < areaval.length; i++) {
				var op = new Option(areaval[i], i);
				areaEle.options.add(op);
			}

		};

        /*點擊市*/
		function chg2(obj) {
			var val = obj.value;
			var areav = area[val01][val];
			areaEle.options.length = 0;
            /*遍歷區*/
			for (i = 0; i < areav.length; i++) {
				var op = new Option(areav[i], i);
				areaEle.options.add(op);
			}

		}

	</script>
</body>

</html>
相關文章
相關標籤/搜索