js实现简单的省市联动效果

<body>
	国家:<select id="country" onchange="getCity()">
		<option selected="selected">请选择</option>
		<option>中国</option>
		<option>美国</option>
		<option>日本</option>
	</select>
	城市:<select id="city">
	</select>
</body>
	<script type="text/javascript">
		var cityArr=new Array(3);
		cityArr[0]=["中国","北京","上海","杭州","济南"];
		cityArr[1]=["美国","纽约","华盛顿","底特律","马达加斯加"];
		cityArr[2]=["日本","东京","大阪","长崎","北海道"];
		function getCity(){
			var options=document.getElementById("country").getElementsByTagName("option");
			var city=document.getElementById("city");
			for(var i=1;i<options.length;i++){
				//通过遍历查找被选择的国家
				if(options[i].selected==true){
					//删除所有的city中的子元素
					while(city.hasChildNodes()){
						city.removeChild(city.firstChild);
					}
					//遍历循环数组中所有的元素,将其创建成option元素添加到city的select中
					for(var j=1;j<cityArr[i-1].length;j++){
						var newOption=document.createElement("option");
						var newText=document.createTextNode(cityArr[i-1][j]);
						newOption.appendChild(newText);
						
						city.appendChild(newOption);
					}
				}
			}
		}
	</script>

猜你喜欢

转载自blog.csdn.net/sheng_mu555/article/details/79199949