/**
* 省市县区三级多级联动
* author:凨来了
*/
jQuery(function($) {
var city=[],cityName=[];
$.fn.city = function (opt) {
var $id = $(this),
options = $.extend({
url: 'data.php?parent_id=',
/*当前ID,设置选中状态*/
selected: null,
/*上级栏目ID*/
parent_id: null,
/*主键ID名称*/
valueName: "id",
/*名称*/
textName: "cn_name",
/*默认名称*/
defaultName: "-----",
/*下级对象ID*/
nextID: null}, opt),selected,_tmp;
if(options.parent_id==null){
_tmp=$id.data('parent_id');
if(_tmp!==undefined){
options.parent_id=_tmp;
}
}
//初始化层
this.init = function () {
if($.inArray($id.attr('id'),cityName)==-1){
cityName.push($id.attr('id'));
}
if(!options.selected){
options.selected=$id.data('selected');
}
$id.append(format(get(options.parent_id)));
};
function get(id) {
if (id !== null && !city[id]) {
getData(id);
return city[id];
}else if (id !== null && city[id]) {
return city[id];
}
return [];
}
function getData(id) {
$.ajax({
url: options.url+ id,
type: 'GET',
async: false,
success: function (d) {
if (d.status == 'y') {
city[id] = d.data;
}
}
});
}
function format(d) {
var _arr = [], r, selected = '';
if (options.defaultName !== null) _arr.push('<option value="">' + options.defaultName + '</option>');
if ($.isArray(d)) for (var v in d) {
r = null;
r = d[v];
selected = '';
if (options.selected && options.selected == (r[options.valueName])) {
selected = 'selected';
}
_arr.push('<option value="' + r[options.valueName] + '" ' + selected + '>' + r[options.textName] + '</option>');
}
return _arr.join('');
}
this.each(function () {
options.nextID && $id.on('change', function () {
var $this = $('#' + options.nextID),id=$(this).attr('id'),i=$.inArray(id,cityName);
$this.html(format(get($(this).val())));
if ($.isArray(cityName)) for (var v in cityName) {
if(v>(i+1)){
$('#'+cityName[v]).html(format());
}
}
});
});
this.init();
}
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>jQuery 省市区多级(三级/四级/五级。。。)联动 BY 凨来了</title>
</head>
<body><dl>
<dt>所在地区:</dt>
<dd>
<select id="province" name="province" class="form-control city-select" data-selected="10" data-parent_id="0"></select>
<select id="city" name="city" class="form-control city-select" data-selected="112" data-parent_id="10"></select>
<select id="county" name="county" class="form-control city-select" data-selected="1387" data-parent_id="112"></select>
</dd>
</dl>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="city.js"></script>
<script type="text/javascript">
$(function(){
$('#province').city({nextID:'city'});
$('#city').city({nextID:'county'});
$('#county').city();
});
</script>
</body>
</html>
demo下载