需求:
对地区进行选择,选择相应的省,就会出现相应范围的市,然后出现相应的范围的县区;如果县不存在,就不现实,自我要求是自己写个简单的插件,方便以后调用;
逻辑:
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 ([email protected]) * @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 有修改!
时间: 2024-10-12 20:19:14