jquery plugin code
;(function ($) { $.fn.extend({ "initcity":function(settings){ var selectid = this.selector; var selectprov = selectid+" .prov"; //省的select var selectcity = selectid+" .city"; //市的select //parameter var sysParas = { provalue:null, //Provide value cityvalue:null //market value }; //assign $.extend(sysParas,settings); //Get the dropdown list data var provcitylist = getOptionData (); $.each(eval(provcitylist), function (i, item) { $(selectprov).append("<option value='" + item.n + "' >" + item.n + "</option>"); }); //Select province drop-down trigger $(selectprov).change(function () { //Get the selected subscript of the province drop-down selection var provindex = $('option:selected', selectprov).index() $(selectcity).empty(); $.each(eval(provcitylist)[provindex].citylist, function (i, item) { $(selectcity).append("<option value='" + item.n + "' >" + item.n + "</option>"); }); }); //Bind selectprov if (sysParas.provalue!=null) { $(selectprov).val(sysParas.provalue); }; //Refresh selectcity $(selectprov).change(); //Bind selectcity if (sysParas.cityvalue!=null) { $(selectcity).val(sysParas.cityvalue); }; } }); function getOptionData(){ var provcitylist = [ { "n": 'All', citylist:[{"n":'all'}] },{ "n": 'Anhui', citylist: [{ "n": 'Anqing' },{ "n": 'Bengbu' },{ "n": 'Bozhou' },{ "n": 'Chaohu' },{ "n": 'Chuzhou ' }] },{ "n": 'Macau', citylist: [{ "n": 'Lobby Area' },{ "n": 'Taipa' },{ "n": 'Fengshun Parish' },{ "n": 'Fatima Parish' } ] },{ "n": 'Beijing', citylist: [{"n":"Changping"},{"n":"Chaoyang"},{"n":"Dongcheng"},{"n":"Daxing"},{"n":"Fangshan "},{"n":"Fengtai"}] },{ "n": 'Chongqing', citylist: [{"n":"Beibei"},{"n":"Banan"},{"n":"Bishan"},{"n":"Chengkou"},{"n" :"Longevity"},{"n":"Dadukou"}] }]; return provcitylist; } })(jQuery);HTML code
<body> <script language="javascript" src="jquery-1.7.1.js"></script> <script language="javascript" src="wxcity.js"></script> <script type="text/javascript"> $(function(){ //$("#citylist").initcity(); //No value set $("#citylist").initcity({ provalue:'Beijing', cityvalue: 'East City' }); }); </script> <span id="citylist"> Region Label: <select class="prov" > </select> <select class="city" ></select> </span> </body>
The data is based on WeChat region selection as an example
Complete code download address: complete example download