首页  >  文章  >  web前端  >  基于jquery & json的省市区联动代码_jquery

基于jquery & json的省市区联动代码_jquery

WBOY
WBOY原创
2016-05-16 17:52:101006浏览

效果演示:



html代码:

复制代码 代码如下:





省市区联动




Demo:















script.js代码:

复制代码 代码如下:

/*
author: elycir
create: 2012-06
description: 省市区三级(二级)联动
*/
$(function () {
var citySelector = function () {
var province = $("#province");
var city = $("#city");
var district = $("#district");
var preProvince = $("#pre_province");
var preCity = $("#pre_city");
var preDistrict = $("#pre_district");
var jsonProvince = "/content/json-array-of-province.js";
var jsonCity = "/content/json-array-of-city.js";
var jsonDistrict = "/content/json-array-of-district.js";
var hasDistrict = true;
var initProvince = "";
var initCity = "";
var initDistrict = "";
return {
Init: function () {
var that = this;
that._LoadOptions(jsonProvince, preProvince, province, null, 0, initProvince);
province.change(function () {
that._LoadOptions(jsonCity, preCity, city, province, 2, initCity);
});
if (hasDistrict) {
city.change(function () {
that._LoadOptions(jsonDistrict, preDistrict, district, city, 4, initDistrict);
});
province.change(function () {
city.change();
});
}
province.change();
},
_LoadOptions: function (datapath, preobj, targetobj, parentobj, comparelen, initoption) {
$.get(
datapath,
function (r) {
var t = ''; // t: html容器
var s; // s: 选中标识
var pre; // pre: 初始值
if (preobj === undefined) {
pre = 0;
} else {
pre = preobj.val();
}
for (var i = 0; i s = '';
if (comparelen === 0) {
if (pre !== "" && pre !== 0 && r[i].code === pre) {
s = ' selected=\"selected\" ';
pre = '';
}
t += '';
}
else {
var p = parentobj.val();
if (p.substring(0, comparelen) === r[i].code.substring(0, comparelen)) {
if (pre !== "" && pre !== 0 && r[i].code === pre) {
s = ' selected=\"selected\" ';
pre = '';
}
t += '';
}
}

}
if (initoption !== '') {
targetobj.html(initoption + t);
} else {
targetobj.html(t);
}
},
"json"
);
}
};
} ();
citySelector.Init();
});

省市区json数据文件:点击下载
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn