DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> 基於jquery & json的省市區聯動代碼
基於jquery & json的省市區聯動代碼
編輯:JQuery特效代碼     
效果演示:



html代碼:

. 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>省市區聯動</title>
<script src="/Scripts/jquery.min.js" type="text/javascript"></script>
<script src="/Scripts/script.js" type="text/javascript"></script>
</head>
<body>
<h2>Demo:</h2>
<select id="province">
<option value="0">請選擇省份</option>
</select>
<select id="city">
<option value="0">請選擇城市</option>
</select>
<select id="district">
<option value="0">請選擇區縣</option>
</select>

<!--下列為初始值(可選,編輯表單時設置)-->
<input type="hidden" value="440000" id="pre_province"/>
<input type="hidden" value="440500" id="pre_city"/>
<input type="hidden" value="440511" id="pre_district"/>

</body>
</html>


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 = "<option value='0'>請選擇省份</option>";
var initCity = "<option value='0'>請選擇城市</option>";
var initDistrict = "<option value='0'>請選擇區縣</option>";
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 < r.length; i++) {
s = '';
if (comparelen === 0) {
if (pre !== "" && pre !== 0 && r[i].code === pre) {
s = ' selected=\"selected\" ';
pre = '';
}
t += '<option value=' + r[i].code + s + '>' + r[i].name + '</option>';
}
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 += '<option value=' + r[i].code + s + '>' + r[i].name + '</option>';
}
}

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

省市區json數據文件:點擊下載

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved