`
sswh
  • 浏览: 163819 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

请您先登录,才能继续操作

省市县三级联动下拉框

阅读更多
写了一个省市县三级联动的下拉框:

先看一下用法:
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;
}
}
4
2
分享到:
评论
4 楼 yuhaibo6646737 2012-10-13  
thanks@
3 楼 ILoveDOUZHOU 2012-08-20  
谢谢,问题解决了。
2 楼 sswh 2012-08-18  
TO  ILoveDOUZHOU :

Area.js中this.select();只是考虑初始化后,如果用户没有调用select()方法的话,
地市的下拉列表没有初始化,看起来不太好看。
去掉也没有什么影响。


如果我将该三级联动下拉框放在修改地址的页面,需要显示初始的三级地址,可以怎么给select赋值?

就是调用select方法,比如:
var area  = new Area('#areaContainer');
area.select(['北京', '海淀区']);

~~~~~~~~~~~~~~
上面的缺点是初始化的话,你要写省市的名字。

所以,之后做了一下重构,主要是按照行政区划代码来保存、初始化下拉列表。
请参考:http://sswh.iteye.com/blog/1551912
1 楼 ILoveDOUZHOU 2012-08-17  
你好。请问Area.js中this.select();  什么作用?
如果我将该三级联动下拉框放在修改地址的页面,需要显示初始的三级地址,可以怎么给select赋值?

相关推荐

Global site tag (gtag.js) - Google Analytics