1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>省市县三级联动</title> 6 <script src="js/province.js">//省数据数组</script> 7 <script src="js/city.js">//市数据数组</script> 8 <script src="js/area.js">//县数据数组</script> 9 <script> 10 window.onload = function () {//页面加载完成 11 var province = document.getElementById("province"); 12 var city = document.getElementById("city"); 13 var area = document.getElementById("area"); 14 for (var i = 0; i < provinces.length; i++) {//向省下拉列表填充数据 15 var option = document.createElement("option");//创建一个option对象 16 option.setAttribute("id", provinces[i].id);//设置option的id属性的值 17 option.setAttribute("value", provinces[i].id);//设置option的value属性的值 18 option.innerHTML = provinces[i].name;//向option中填充内容 19 province.appendChild(option);//将potion添加到省列表中 20 } 21 province.onchange = function () {//省下拉列表域改变事件 22 city.innerHTML = " <option value="0">---请选择---</option>"; 23 var array = citys[province.value];//获取省对应的市的数组 24 for (var i = 0; i < array.length; i++) {//向市下拉列表填充数据 25 var option = document.createElement("option"); 26 option.setAttribute("value", array[i].id); 27 option.setAttribute("id", array[i].id); 28 option.innerHTML = array[i].name; 29 city.appendChild(option); 30 } 31 } 32 city.onchange = function () {//市下拉列表域改变事件 33 area.innerHTML = " <option value="0">---请选择---</option>"; 34 var array = areas[city.value];//获取市对应的县的数组 35 for (var i = 0; i < array.length; i++) {//向县下拉列表填充数据 36 var option = document.createElement("option"); 37 option.setAttribute("value", array[i].id); 38 option.setAttribute("id", array[i].id); 39 option.innerHTML = array[i].name; 40 area.appendChild(option); 41 } 42 } 43 area.onchange = function () {//县下拉列表域改变事件 44 var data1 = document.getElementById(province.value).innerHTML;//获取省的值 45 var data2 = document.getElementById(city.value).innerHTML;//获取市的值 46 var data3 = document.getElementById(area.value).innerHTML;//获取县的值 47 document.getElementById("data").innerHTML = "地址:" + data1 + data2 + data3;//向界面填充结果 48 } 49 } 50 </script> 51 </head> 52 <body> 53 省 54 <select id="province"> 55 <option value="0">---请选择---</option> 56 </select> 57 市 58 <select id="city"> 59 <option value="0">---请选择---</option> 60 </select> 61 县 62 <select id="area"> 63 <option value="0">---请选择---</option> 64 </select> 65 <div id="data"> 66 67 </div> 68 </body> 69 </html>
数据样式:
省
1 var provinces = [{ 2 "name": "北京市", 3 "id": "110000" 4 }, { 5 "name": "天津市", 6 "id": "120000" 7 }, { 8 "name": "河北省", 9 "id": "130000" 10 },..................
市
1 var citys = { 2 "110000": [ 3 { 4 "province": "北京市", 5 "name": "市辖区", 6 "id": "110100" 7 } 8 ], 9 "120000": [ 10 { 11 "province": "天津市", 12 "name": "市辖区", 13 "id": "120100" 14 } 15 ],...................
县
1 var areas = { 2 "110100": [ 3 { 4 "city": "市辖区", 5 "name": "东城区", 6 "id": "110101" 7 }, 8 { 9 "city": "市辖区", 10 "name": "西城区", 11 "id": "110102" 12 },..................