当前位置: 代码迷 >> Web前端 >> 省地县三级联动下拉框
  详细解决方案

省地县三级联动下拉框

热度:108   发布时间:2012-08-16 12:02:15.0
省市县三级联动下拉框
写了一个省市县三级联动的下拉框:

先看一下用法:
test.html,依赖于jquery和一个JS文件。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="../js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="Area.js"></script>
<style>
body{font-size:14px; font-family:simsun;margin:0;}
</style>
</head>
<body>
<span id="areaContainer"></span>
<input id="getValueBtn" type="button" value="getValue">
</body>
</html>
<script type="text/javascript">
$(function(){
	Area.init('area.json');
	var area  = new Area('#areaContainer');
	area.select(['北京', '海淀区']);
	
	$('#getValueBtn').click(function(){
		alert(area.getAddress());
	});
});
</script>


Area.js
function Area(selector){
	if(!Area.ALL_AREAS){
		throw new Error('areas not init!');
	}

	this.selector = selector;
	$(this.selector).html('<select/><select/><select/>');
	
	var $province = this._getElement(Area.code.PROVINCE);
	var $city = this._getElement(Area.code.CITY);
	var $county = this._getElement(Area.code.COUNTY);
	
	var self = this;
	$province.change(function(){
		var province = this.value;
		$city.html(self._getOptions([province]));
		var city = $city.val();
		$county.html(self._getOptions([province, city]));
	});
	$city.change(function(){
		var province = $province.val();
		var city = this.value;
		$county.html(self._getOptions([province, city]));
	});
	$province.html(self._getOptions());
	this.select();
}

$.extend(Area, {
	ALL_AREAS : null,
	code : {
		PROVINCE : 0,
		CITY : 1,
		COUNTY : 2
	},
	init : function(url){
		if(Area.ALL_AREAS) return;
		Area.ALL_AREAS = $.parseJSON($.ajax({
			url : url,
			async : false
		}).responseText);
	}
});

Area.prototype = {
	
	_getElement : function(code){
		return $(this.selector).find('select').eq(code);
	},
	
	select : function(address){
		var address = address || [];

		var $province = this._getElement(Area.code.PROVINCE);
		var $city = this._getElement(Area.code.CITY);
		var $county = this._getElement(Area.code.COUNTY);

		var province = address.length < 1 ? '' : address[0]; 
		$province.val(province);
		$city.html(this._getOptions([province]));

		var city = address.length < 2 ? '' : address[1]; 
		$city.val(city);
		$county.html(this._getOptions([province, city]));

		var county = address.length < 3 ? '' : address[2]; 
		$county.val(county);
	},
	
	getAddress : function(){
		var $province = this._getElement(Area.code.PROVINCE);
		var $city = this._getElement(Area.code.CITY);
		var $county = this._getElement(Area.code.COUNTY);
		return [$province.val(), $city.val(), $county.val()];		
	},
	
	_getAreaName : function(area){
		if(typeof(area) == 'string') return area;
		for(var o in area){
			return o;
		}
	},
	
	_getAreas : function(areaName, superAreas){
		for(var i=0; i<superAreas.length; i++){
			if(this._getAreaName(superAreas[i]) == areaName)
				return superAreas[i][areaName] || [];
		}
		return [];
	},
	
	_getAreasByAddress : function(address){
		var areas = Area.ALL_AREAS;
		for(var i=0; i<address.length; i++){
			areas = this._getAreas(address[i], areas);
		}
		return areas;
	},
	
	_getAreaNames : function(address){
		var areas = this._getAreasByAddress(address);
		var areaNames = [];
		for(var i=0; i<areas.length; i++){
			areaNames.push(this._getAreaName(areas[i]));
		}
		return areaNames;
	},
	
	_getOption : function(optionName){
		return '<option value="' + optionName + '">' + optionName + '</option>';
	},
	
	_getOptions : function(address){
		var address = address || [];
		var areaNames = this._getAreaNames(address);
		var options = '<option value="">请选择</option>';
		for(var i=0; i<areaNames.length; i++){
			options += this._getOption(areaNames[i]);
		}
		return options;
	}

};


area.json的示例:
[{"北京" : null
}, {"广东" : 
	["广州", {"珠海" : ["香洲", "金湾", "斗门"]
	}]
}]


另外,提示一下,在chrome下面测试的时候,记得要加启动参数(允许本地ajax访问) --allow-file-access-from-files

从网上找了一份全国行政区划的EXCEL文件,转成了area.json数据:
public class Test {
public static void main(String[] args) throws Exception {
	Workbook workbook = Workbook.getWorkbook(Test.class.getResourceAsStream("行政区划.xls"));
	Sheet sheet = workbook.getSheet(0);

	List<Map> roots = new ArrayList<Map>();
	Map<String, List> lastProvince = null;
	Map<String, List> lastCity = null;
	for (int i = 2; i < Integer.MAX_VALUE; i++) {
		String province = trimToNull(sheet.getCell(0, i).getContents());
		String city = trimToNull(sheet.getCell(2, i).getContents());
		String county = trimToNull(sheet.getCell(3, i).getContents());
		if (province == null && city == null && county == null) break;

		if (province != null) {
			if (city == null) throw new RuntimeException("数据错误!" + province + "," + city + "," + county);

			lastProvince = new HashMap();
			roots.add(lastProvince);
			List<Map> cities = new ArrayList<Map>();
			lastProvince.put(province, cities);
		}

		if (city != null) {
			lastCity = new HashMap();
						lastProvince.values().iterator().next().add(lastCity);
			List<String> counties = new ArrayList<String>();
			lastCity.put(city, counties);
		}

		lastCity.values().iterator().next().add(county);
	}
	workbook.close();
	ObjectMapper mapper = new ObjectMapper();
	mapper.writeValue(System.out, roots);
}

static String trimToNull(String text) {
	if (text == null) return null;
	text = text.replaceAll("\\s", "");
	return text.length() == 0 ? null : text;
}
}
  相关解决方案