省市区三级联动 创建3个select,每次给对应的select里new对应的option 需要注意的是,每次select变化的时候,需要清空之前的状态,否者会有bug 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p align="center"> 省:<select name="" id="sel1"> <option value="">请选择</option> </select> 市:<select id="sel2"></select> 区:<select id="sel3"></select> </p> 你选择的地址是:<h1 id="address"></h1></body><script src="city.js" type="text/javascript" charset="utf-8"></script><script> var sel1 = document.getElementById("sel1") var sel2 = document.getElementById("sel2") var sel3 = document.getElementById("sel3") var h1 = document.getElementById('address') var cityArr = [] var areaArr = [] provice.forEach(v => { var option = new Option(v.name); sel1.options.add(option); }) sel1.onchange = function () { console.log(this.selectedIndex); sel1Index = this.selectedIndex - 1; sel2.options.length = 0; sel3.options.length = 0; if (sel1Index !== -1) { cityArr = provice[sel1Index].city; cityArr.forEach(v => { var option = new Option(v.name); sel2.options.add(option); }) areaArr = cityArr[0].districtAndCounty // console.log(areaArr); areaArr.forEach(v => { var option = new Option(v); sel3.options.add(option); }) h1.innerText = `${provice[sel1Index].name}${cityArr[0].name}${areaArr[0]}` } else { h1.innerText = ""; } } var sel2Index = 0; sel2.onchange = function () { sel2Index = this.selectedIndex; areaArr = cityArr[sel2Index].districtAndCounty; // console.log(areaArr); sel3.options.length = 0; areaArr.forEach(v => { var option = new Option(v); sel3.options.add(option); }) h1.innerText = `${provice[sel1Index].name}${cityArr[sel2Index].name}${areaArr[0]}` } var sel3Index = 0; sel3.onchange = function () { sel3Index = this.selectedIndex; // console.log(sel3Index); h1.innerText = `${provice[sel1Index].name}${cityArr[sel2Index].name}${areaArr[sel3Index]}` }</script></html>