做项目的时候写了一个很笨的省市区三级联动,还没优化,先记录一下:
<html> <head> <meta charset="utf-8"> <script type="text/javascript" src="jquery1.71/jquery-1.7.1.min.js"></script> </head> <body> <div> <select class="add-on" name="province" id="province"></select> <select class="add-on" name="city" id="city"></select> <select class="add-on" name="district" id="district"></select> </div> <script type="text/javascript"> data= new Object(); jQuery=$; data.user_area={'province':[{'name_ch':'湖北','_id':100000},{'name_ch':'湖南','_id':200000}], 'city':[{'name_ch':'武汉','_id':101000,'fid':100000}, {'name_ch':'长沙','_id':201000,'fid':200000}, {'name_ch':'张家界','_id':200200,'fid':200000}], 'district':[{'name_ch':'武昌市','_id':100110,'fid':101000}, {'name_ch':'雨花区','_id':200210,'fid':201000}, {'name_ch':'桑植县','_id':200220,'fid':200200}, {'name_ch':'慈利县','_id':200210,'fid':200200}]}; console.log(data.user_area); jQuery(document).ready(function(){ for (p in data.user_area['province']){ jQuery('#province').append('<option value='+data.user_area['province'][p]['_id']+'>'+data.user_area['province'][p]['name_ch']+'</option>') } for (c in data.user_area['city']){ if (data.user_area['city'][c]['fid'] == data.user_area['province'][0]['_id']){ jQuery('#city').append('<option value='+data.user_area['city'][c]['_id']+'>'+data.user_area['city'][c]['name_ch']+'</option>') } } for (c in data.user_area['district']){ if (data.user_area['district'][c]['fid'] == data.user_area['city'][0]['_id']){ jQuery('#district').append('<option value='+data.user_area['district'][c]['_id']+'>'+data.user_area['district'][c]['name_ch']+'</option>') } } selectArea(data); function selectArea(data){ jQuery('#province').change(function(){ jQuery('#city').empty(); for (c in data.user_area['city']){ if (data.user_area['city'][c]['fid'] ==jQuery('#province').find('option:selected').val()) { jQuery('#city').append('<option value='+data.user_area['city'][c]['_id']+'>'+data.user_area['city'][c]['name_ch']+'</option>') } } jQuery('#district').empty(); for( d in data.user_area['district']){ if(data.user_area['district'][d]['fid']==jQuery('#city').find('option:selected').val()){ jQuery('#district').append('<option value='+data.user_area['district'][d]['_id']+'>'+data.user_area['district'][d]['name_ch']+'</option>') } } }); jQuery('#city').change(function(){ jQuery('#district').empty(); for( d in data.user_area['district']){ if(data.user_area['district'][d]['fid']==jQuery('#city').find('option:selected').val()){ jQuery('#district').append('<option value='+data.user_area['district'][d]['_id']+'>'+data.user_area['district'][d]['name_ch']+'</option>') } } }); } }); </script> </body> </html>