省市级联菜单[百度版]

在浏览器中实现省市级联菜单的效果已经非常常见了。最令我满意的还是百度的省市级联,百度将省市数据放在了一个单独的.js文件中,我们可以直接引入进来:

<script type="text/javascript" src="http://passport.baidu.com/js/sitedata_bas.js" charset="GBK"></script>

然后,再贴上这样一段JS代码,这段代码是我自己写的,因为百度将这部分的JS代码压缩处理了。

var Utils = {};
Utils.addEvent = function(el, type, func) {
	if (document.addEventListener) {
		el.addEventListener(type, func, false);
	} else if (document.attachEvent) {
		el.attachEvent('on' + type, func);
	}
};
Utils.addEvent(window, 'load', function() {
	var region1 = document.getElementById("region1");
	var region2 = document.getElementById("region2");
	var region3 = document.getElementById("region3");
	for ( var i = 0; i < arrCity.length; i++) {
		region1.options[i] = new Option(arrCity[i].name, arrCity[i].name);
	}
	region2.options[0] = new Option("请选择", "请选择");
	region3.options[0] = new Option("请选择", "请选择");
	region3.style.display = "none";
	Utils.addEvent(region1, 'change', function() {
		var region1_obj = arrCity[region1.selectedIndex];
		var region2_arr = region1_obj.sub;
		region2.options.length = 0;
		region3.options.length = 0;
		region3.style.display = "none";
		for ( var i = 0; i < region2_arr.length; i++) {
			region2.options[i] = new Option(region2_arr[i].name, region2_arr[i].name);
		}
	});
	Utils.addEvent(region2, 'change', function() {
		var region1_obj = arrCity[region1.selectedIndex];
		var region2_obj = region1_obj.sub[region2.selectedIndex];
		var region3_arr = region2_obj.sub;
		if (region2_obj.type == 0) {
			region3.options.length = 0;
			region3.style.display = "inline";
			for ( var i = 0; i < region3_arr.length; i++) {
				region3.options[i] = new Option(region3_arr[i].name, region3_arr[i].name);
			}
		} else {
			region3.style.display = "none";
		}
	});
});
在HTML的body部分需要有三个select元素:

<form>
<table>
	<tr>
		<th>地址</th>
		<td>
			<select id="region1" name="region1"></select>
			<select id="region2" name="region2"></select>
			<select id="region3" name="region3"></select>
		</td>
	</tr>
	<tr>
		<th colspan="2"><input type="submit" value="提交" /></th>
	</tr>
</table>
</form>
这样就做好了!

省市级联菜单[百度版]

你可能感兴趣的:(JavaScript,省市级联)