<html lang="en"><head>
<meta charset="UTF-8">
<title>省市下拉联动插件</title>
<style>
#warp {
width: 230px;
height: 80px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -130px;
box-shadow: 1px 1px #3A393A;
border: 1px solid #222;
font-size: 13px;
line-height: 13px;
}
#province {
margin: 30px 0 0 30px;
float: left;
}
#city {
float: right;
margin: 30px 30px 0 0;
}
</style>
<script src="js/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="warp">
<select id="province">
<option data-extra="100000">北京市</option><option data-extra="300000">天津市</option></select>
<select id="city">
<option data-extra="100003">北辰区</option><option data-extra="100002">红桥区</option><option data-extra="100001">河西区</option></select>
</div>
<script type="text/javascript">
//插件基础代码
;
(function ($) {
$.fn.extend({
"citylist": function (params) {
params = $.extend({
param: 'this is a param'
}, params);
var target = $(this);
if (!target.length) {
return this;
} else if (target.length == 1) {
} else if (target.length == 2) {
var province = target.eq(0);
var city = target.eq(1);
var html = [], oItem;
for(var item in params.data){
oItem = params.data[item];
console.log(oItem)
html.push('<option data-extra="'+oItem['id']+'">'+oItem['name']+'</option>');
}
html = html.join('');
province.find('option').remove();
province.append(html);
var provinces = province.find('option');
province.on('change',function(){
var curSelect = $(this).val();
provinces.each(function(k,v){
if ($(v).val() == curSelect){
return (function(v){
var extra = $(v).attr('data-extra');
var html = [], oItem;
for(var item in params.data){
oItem = params.data[item];
if(oItem['id'] == extra && oItem.children){
oItem = oItem.children;
for(var sItem in oItem){
html.push('<option data-extra="'+oItem[sItem]['id']+'">'+oItem[sItem]['name']+'</option>');
}
break;
}
}
html = html.join('');
city.find('option').remove();
city.append(html);
}(v));
}
})
}).trigger('change');
}
return this;
}
});
})(jQuery, 'SOULTEARY.COM');
//插件调用代码
;
$(function () {
var data = [
{'name': '北京市', id: 100000, children: [
{'name': '海淀区', id: 100003},
{'name': '西城区', id: 100002},
{'name': '东城区', id: 100001}
]},
{'name': '天津市', id: 300000, children: [
{'name': '北辰区', id: 100003},
{'name': '红桥区', id: 100002},
{'name': '河西区', id: 100001}
]}
];
$('#province, #city').citylist({data:data});
});
</script>
</body></html>