需求:
對地區進行選擇,選擇相應的省,就會出現相應范圍的市,然后出現相應的范圍的縣區;如果縣不存在,就不現實,自我要求是自己寫個簡單的插件,方便以后調用;
邏輯:
1.通過div的類名來獲取,其下的select標簽;
2.通過聲明臨時變量,用來保存option內容,並通過$.each()來遍歷json然后添加到select中;
3.如果某個市沒有縣,就先判斷json中有沒記錄,如果沒有就不現實,有就繼續執行下面代碼;
4.用change事件來控制三個selet之間的聯系;
5.通過ajax $.getJSON,來觸發省份事件,然后通過省份select的改變,來觸發市區,以此類推;
實現:
json數據
[
{"p":"江西省",
"c":[
{"ct":"南昌市",
"d":[
{"dt":"西湖區"},
{"dt":"東湖區"},
{"dt":"高新區"}
]},
{"ct":"贛州市",
"d":[
{"dt":"瑞金縣"},
{"dt":"南豐縣"},
{"dt":"全南縣"}
]}
]},
{"p":"北京",
"c":[
{"ct":"東城區"},
{"ct":"西城區"}
]},
{"p":"河北省",
"c":[
{"ct":"石家庄",
"d":[
{"dt":"長安區"},
{"dt":"橋東區"},
{"dt":"橋西區"}
]},
{"ct":"唐山市",
"d":[
{"dt":"灤南縣"},
{"dt":"樂亭縣"},
{"dt":"遷西縣"}
]}
]}
]
html代碼
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>select</title>
<meta name="description" content="">
<meta name="keywords" content="">
<script type="text/javascript" src="jquery.js"></script>
<script src = "areaSelect.js"></script>
<link href="" rel="stylesheet">
<style>
.sel{
width:300px;
margin:0 auto;
}
</style>
</head>
<body>
<div class="sel">
<select class="province">
<option>請選擇</option>
</select>
<select class="city">
<option>請選擇</option>
</select>
<select class="district">
<option>請選擇</option>
</select>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(".sel").areaSelect({
"jsonUrl":"area.json"
})
})
</script>
jquery插件
/**
*
* @authors Your Name (you@example.org)
* @date 2015-09-13 01:54:25
* @version $Id$
*/
(function($){
$.fn.areaSelect = function(options){
var settings = $.extend({
"jsonUrl":"json"
},options);
return this.each(function(){
var url = options.jsonUrl;
var addJson;
var tHtml = "";
var op = $(this).find(".province");
var oc = $(this).find(".city");
var od = $(this).find(".district");
//初始化
var province = function(){
$.each(addJson,function(i,province){
tHtml += "<option value = '"+province.p+"'>"+province.p+"</option>";
});
op.html(tHtml);
city();
}
var city = function(){
var tHtml="";
var n = op.get(0).selectedIndex;
$.each(addJson[n].c,function(i,city){
tHtml += "<option value='"+city.ct+"''>"+city.ct+"</option>";
});
oc.html(tHtml);
district();
}
var district = function(){
var tHtml="";
var n = op.get(0).selectedIndex;
var m = oc.get(0).selectedIndex;
if(typeof (addJson[n].c[m].d) == "undefined"){
od.css("display","none")
}else{
od.css("display","inline");
$.each(addJson[n].c[m].d,function(i,district){
tHtml += "<option value='"+district.dt+"'>"+district.dt+"</option>"
});
od.html(tHtml);
}
}
op.change(function(){
city();
})
oc.change(function(){
district()
});
$.getJSON(settings.jsonUrl,function(data){
addJson = data;
province()
})
})
}
})(jQuery)
轉載自:http://www.cnblogs.com/afuge/archive/2013/06/08/3127172.html 有修改!
