天天看点

纯js三级联动菜单

今天用js做了一个三级联动菜单,发现这种东西还是蛮费脑力的,要被这个对象给搞蒙了!以下是我分享出来的代码,希望对大家有帮助!

<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>三级联动菜单</title>
</head>
<body>
	<form action="" name="form1">
		<select name='province' οnchange="getCity();">
			<option value="">==请选择省份==</option>

		</select>
		<select name='city' οnchange='getCountry();'>
			<option value="">==请选择城市==</option>

		</select>
		<select  name="country">
			<option value="">==请选择区域==</option>

		</select>

	</form>
	<script type="text/javascript">
		var array=[
					{name:'湖南省',cities:[{name:'长沙市',countries:['岳麓区','天心区','雨花区','望城区']},
									 {name:'岳阳市',countries:['平江县','岳阳楼','洞庭湖']}

					]},
					{name:'湖北省',cities:[{name:'武汉市',countries:['武汉区','武冈区','硅谷区','东湖区']},
										   {name:'武冈市',countries:['黄花区','黄花去1','黄花区12','黄花去12']}

					]},
					{name:'北京省',cities:[{name:'北京市',countries:['北京1区','北京1区','北京1区','北京1区']},
											{name:'北京市',countries:['北京2区','北京2区','北京2区','北京2区']}
					]}


		]
			var province=document.form1.province;
			var city=document.form1.city;
			var country=document.form1.country;
		window.οnlοad=function(){
			for(var i=0;i<array.length;i++){
				province[i+1]=new Option(array[i].name,array[i].name);
			}
		}
		function getCity(){
			var proIndex=province.selectedIndex;
			alert(proIndex);
			var selectedCity=array[proIndex-1].cities;
			for(var i=0;i<selectedCity.length;i++){
				city[i+1]=new Option(selectedCity[i].name,selectedCity[i].name);
			}

		}
		function getCountry(){
			var proIndex=province.selectedIndex;
			var selectedCity=array[proIndex-1].cities;
			var cityIndex=city.selectedIndex;
			var selectedCountry=selectedCity[cityIndex-1].countries;
			for(var i=0;i<selectedCountry.length;i++){
				country[i+1]=new Option(selectedCountry[i],selectedCountry[i])
			}
		}
	</script>
</body>
</html>