html:
<!-- 省 --> <select name="" class="a"> <option value="">--请输入--</option> </select> <!-- 市 --> <select name="" class="a"> <option value="">--请输入--</option> </select> <!-- 县 --> <select name="" class="a"> <option value="">--请输入--</option> </select>
css:
* { padding: 0; margin: 0; } .a { border-radius: 20px; }
js:
// 数据 let data = [{ "name": "河南省", "value":1, "child": [{ "name": "郑州", "child": [{ "name": "金水区" }, { "name": "二七区" } ] }, { "name": "新乡市", "child": [{ "name": "红旗区" }, { "name": "获嘉县" } ] } ] }, { "name": "山西省", "value":2, "child": [{ "name": "晋城", "child": [{ "name": "阳城县" }, { "name": "沁水县" } ] }, { "name": "太原", "child": [{ "name": "晋源区" }, { "name": "万柏林区" } ] } ] } ] // 获取到class let arr = document.getElementsByClassName("a")[0]; let arra = document.getElementsByClassName("a")[1]; let arrb = document.getElementsByClassName("a")[2]; let a; // for循环出省 for (let i = 0; i < data.length; i++) { let shen = new Option(data[i].name); arr.appendChild(shen); } // 获取到里面的内容 arr.onchange = function(){ // 每次数据渲染之前长度初始化 arra.options.length = 1; // 获取到arr的下标 let index = arr.selectedIndex; // for循环出下标对应的值(index获取到的值为数组的值所以要减一) for( let i = 0; i < data[index-1].child.length; i++){ // 创建一个子节点,输出里面的子元素第i个的name let yu = new Option(data[index-1].child[i].name); // 渲染到页面 arra.appendChild(yu); } a = index; } arra.onchange = function(){ arrb.options.length = 1; let indexs = arra.selectedIndex; for( let i = 0; i < data[a-1].child[indexs-1].child.length; i++){ let th = new Option(data[a-1].child[indexs-1].child[i].name); arrb.appendChild(th); } }