一、html部分
<select name="" id="province" class="li_address">
<option value="0">请选择</option>
</select>
<select name="" id="citys">
<option value="0">请选择</option>
</select>
<select name="" id="area">
<option value="0">请选择</option>
</select>
二、js部分
var pIndex = 0;
var province = document.getElementById("province");
var citys = document.getElementById("citys");
var area = document.getElementById("area");
function showProvince(){
let l = cityData.length
for(let i = 0; i < l;i++){
let op = ''
op = document.createElement('option')
let txt=document.createTextNode(cityData[i].text); //创建文本节点
op.appendChild(txt);
let valueattr=document.createAttribute("value"); //创建属性节点
let dataattr=document.createAttribute("data-value"); //创建属性节点
valueattr.value=cityData[i].text; //给属性节点设置值
dataattr.value=cityData[i].value; //给属性节点设置值
op.setAttributeNode(valueattr);
op.setAttributeNode(dataattr);
province.appendChild(op)
}
}
showProvince()
province.onchange = function(e){
changeProvince(e.target)
}
citys.onchange = function(e){
changeCitys(e.target)
}
function changeProvince(obj){
let objIndex = Number(obj.selectedIndex)- 1
pIndex = objIndex
let chind = cityData[objIndex].children;
let areaChind = cityData[objIndex].children[0].children;
citys.options.length = 0;
area.options.length = 0;
for (let i = 0; i < chind.length; i++) {
let op = ''
op = document.createElement('option')
let txt=document.createTextNode(chind[i].text);
op.appendChild(txt);
let valueattr=document.createAttribute("value");
let dataattr=document.createAttribute("data-value");
valueattr.value=chind[i].text;
dataattr.value=chind[i].value;
op.setAttributeNode(valueattr);
op.setAttributeNode(dataattr);
citys.appendChild(op)
}
if(areaChind.length >0){
for (let i = 0; i < areaChind.length; i++) {
let op = ''
op = document.createElement('option')
let txt=document.createTextNode(areaChind[i].text);
op.appendChild(txt);
let valueattr=document.createAttribute("value");
let dataattr=document.createAttribute("data-value");
valueattr.value=areaChind[i].text;
dataattr.value=areaChind[i].value;
op.setAttributeNode(valueattr);
op.setAttributeNode(dataattr);
area.appendChild(op)
}
}else{
let op = ''
op = document.createElement('option')
let txt=document.createTextNode('暂无');
op.appendChild(txt);
area.appendChild(op)
}
}
function changeCitys(obj){
area.options.length = 0;
let objIndex = Number(obj.selectedIndex)
let chind = cityData[pIndex].children[objIndex].children;
for (let i = 0; i < chind.length; i++) {
let op = ''
op = document.createElement('option')
let txt=document.createTextNode(chind[i].text);
op.appendChild(txt);
let valueattr=document.createAttribute("value");
let dataattr=document.createAttribute("data-value");
valueattr.value=chind[i].text;
dataattr.value=chind[i].value;
op.setAttributeNode(valueattr);
op.setAttributeNode(dataattr);
area.appendChild(op)
}
}
三、省市区数据
https://blog.youkuaiyun.com/MagicWing_zs/article/details/83550316