组件的初始化:
初始化时可传入已有的数据进行展示。
var ele = {
"province" : "山东",
"city" : "临沂",
"county" : "郯城县"
}
$("#linkage").provincialLinkage(ele);
js组件中的数据来源为本地的citys.json,网上可下载,或者联系我要。
js组件:
$.fn.extend({
"provincialLinkage":function(ele){
var _this = $(this);
$.getJSON("js/citys.json",function(data){
var _index = 0;
var _indexcity = 0
for (var i = 0; i < data.length; i++) {
var _pro = '<option value="'+data[i].name+'">'+data[i].name+'</option>';
_this.find(".province").append(_pro);
}
if(ele.province && ele.province != ""){
$(".province option[value='"+ele.province+"']").attr("selected",true);
var _p = _this.find(".province");
_index = _p.find("option:selected").index();
_this.find(".city option:gt(0)").remove();
_this.find(".county option:gt(0)").remove();
var _city = data[(_index-1)].child;
for (var i = 0; i < _city.length; i++) {
var _citys = '<option value="'+_city[i].name+'">'+_city[i].name+'</option>';
_this.find(".city").append(_citys);
}
}
/*获取选定的省份*/
_this.find(".province").change(function(){
_index = $(this).find("option:selected").index();
_this.find(".city option:gt(0)").remove();
_this.find(".county option:gt(0)").remove();
var _city = data[(_index-1)].child;
for (var i = 0; i < _city.length; i++) {
var _citys = '<option value="'+_city[i].name+'">'+_city[i].name+'</option>';
_this.find(".city").append(_citys);
}
})
if (ele.city && ele.city != "") {
$(".city option[value='"+ele.city+"']").attr("selected",true);
var _c = _this.find(".city");
_indexcity = _c .find("option:selected").index();
_this.find(".county option:gt(0)").remove();
var _county = data[(_index-1)].child[(_indexcity-1)].child;
for (var i = 0; i < _county.length; i++) {
var _countys = '<option value="'+_county[i].value+'">'+_county[i].value+'</option>';
_this.find(".county").append(_countys);
}
}
/*获取选定城市*/
_this.find(".city").change(function(){
_indexcity = $(this).find("option:selected").index();
_this.find(".county option:gt(0)").remove();
var _county = data[(_index-1)].child[(_indexcity-1)].child;
for (var i = 0; i < _county.length; i++) {
var _countys = '<option value="'+_county[i].value+'">'+_county[i].value+'</option>';
_this.find(".county").append(_countys);
}
})
if(ele.county && ele.county != ""){
$(".county option[value='"+ele.county+"']").attr("selected",true);
}
});
}
})
html部分:
<div id="linkage">
<select name="province" class="province">
<option value="" selected="selected">请选择</option>
</select>
<select name="city" class="city">
<option value="" selected="selected">请选择</option>
</select>
<select name="county" class="county">
<option value=""selected="selected">请选择</option>
</select>
</div>
css部分:
select{
line-height: 28px;
height: 28px;
width: 130px;
border-radius: 2px;
border-color: #ddd;
padding: 0 10px;
}