js三级联动制作
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <label for="country">省:</label> <select id="province" onchange="citys()"> <option value="">请选择省</option> </select> <label for="country">市:</label> <select id="city" onchange="areas()"> <option value="">请选择市</option> </select> <label for="country">区:</label> <select id="area" onchange="aler()"> <option value="">请选择区</option> </select> <script> let province = document.getElementById('province'); let city = document.getElementById('city'); let area = document.getElementById('area'); let data; let xhr = new XMLHttpRequest(); xhr.open('get', 'js/area.json', true); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { let text = xhr.responseText; console.log(text); data = JSON.parse(text); console.log(data); provinces(data); } } function provinces(data) { let str = ""; for (let i = 0; i < data.length; i++) { str += `<option value="${data[i].name}">${data[i].name}</option>` } province.innerHTML += str; } function citys() { console.log(data); let str = "<option value=''>请选择市</option>"; let pro = province.value; for (let i = 0; i < data.length; i++) { if (pro == data[i].name) { console.log(data[i]); for (let j = 0; j < data[i].city.length; j++) { str += `<option value="${data[i].city[j].name}">${data[i].city[j].name}</option>` } city.innerHTML = str; } } } function areas() { let str = '<option value="">请选择区</option>'; let pro = province.value; let cityes = city.value; for (let i = 0; i < data.length; i++) { if (pro == data[i].name) { console.log(data[i]); for (let j = 0; j < data[i].city.length; j++) { if (cityes == data[i].city[j].name) { for (let o = 0; o < data[i].city[j].area.length; o++) { str += `<option value="${data[i].city[j].area[o]}">${data[i].city[j].area[o]}</option>` } area.innerHTML = str; } } } } } function aler() { let pro = province.value; let cityes = city.value; let areas = area.value; console.log(pro); setTimeout(function() { alert(pro + cityes + areas) }, 0) } </script> </body> </html>
js三级联动的假数据
[ { "name": "广东省", "city": [{ "name": "广州市", "area": [ "天河区", "越秀区" ] }, { "name": "深圳市", "area": [ "福田区", "南山区" ] } ] }, { "name": "河南省", "city": [{ "name": "新乡", "area": [ "凤泉区 ", "红旗区 " ] }, { "name": "郑州", "area": [ "二七区", "中原区" ] } ] } ]