上一篇介绍了 Chosen 的使用,这篇介绍联动。看代码:
var addressResolve = function (options) {
//检测用户传进来的参数是否合法
if (!isValid(options))
return this; //默认参数
var defaluts = {
proId: 'divProv',
cityId: 'divCity',
areaId: 'divArea'
}; var opts = $j.extend({}, defaluts, options);//使用jQuery.extend 覆盖插件默认参数 var addressInfo = this;
this.provInfo = $j("#" + opts.proId);//省份select对象
this.cityInfo = $j("#" + opts.cityId);//城市select对象
this.areaInfo = $j("#" + opts.areaId);//区县select对象 /*省份初始化方法*/
this.provInfoInit = function () {
var proOpts = "";
$j.each(provinceJson, function (index, item) {
proOpts += "<option value='" + item.ProID + "'>" + item.name + "</option>";
});
addressInfo.provInfo.append(proOpts); addressInfo.provInfo.chosen(); //初始化chosen
addressInfo.cityInfo.chosen();//初始化chosen
addressInfo.areaInfo.chosen();//初始化chosen
}; /*城市选择绑定方法*/
this.selectCity = function () {
addressInfo.cityInfo.empty();
addressInfo.cityInfo.append("<option value=选择城市>选择城市</option>");
addressInfo.areaInfo.empty();
addressInfo.areaInfo.append("<option value=选择区县>选择区县</option>");
if (addressInfo.provInfo.val() == "选择省份") { //选择无效时直接返回
addressInfo.cityInfo.trigger("liszt:updated");
addressInfo.areaInfo.trigger("liszt:updated");
return;
}
var provId = addressInfo.provInfo.val();//获取选择的省份值
var cityOpts = "";
$j.each(cityJson, function (index, item) {
if (item.ProID == provId) {
cityOpts += "<option value='" + item.CityID + "'>" + item.name + "</option>";
}
});
addressInfo.cityInfo.append(cityOpts);
addressInfo.cityInfo.trigger("liszt:updated");
addressInfo.areaInfo.trigger("liszt:updated");
}; /*区县选择绑定方法*/
this.selectArea = function () {
if (addressInfo.cityInfo.val() == "选择城市") return;
addressInfo.areaInfo.empty();
addressInfo.areaInfo.append("<option value=选择区县>选择区县</option>");
var cityId = addressInfo.cityInfo.val();//获取选择的城市值
var areaOpts = "";
$j.each(areaJson, function (index, item) {
if (item.CityID == cityId) {
areaOpts += "<option value='" + item.Id + "'>" + item.DisName + "</option>";
}
});
addressInfo.areaInfo.append(areaOpts);
addressInfo.areaInfo.trigger("liszt:updated");
}; /*对象初始化方法*/
this.init = function () {
addressInfo.provInfo.append("<option value=选择省份>选择省份</option>");
addressInfo.cityInfo.append("<option value=选择城市>选择城市</option>");
addressInfo.areaInfo.append("<option value=选择区县>选择区县</option>"); addressInfo.provInfoInit();
addressInfo.provInfo.bind("change", addressInfo.selectCity);
addressInfo.cityInfo.bind("change", addressInfo.selectArea);
} //私有方法,检测参数是否合法
function isValid(options) {
return !options || (options && typeof options === "object") ? true : false;
}
}