1
在这里插入代码片
<!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>
<select name="" id="" class="province">
<option>--请选择城市--</option>
</select>
<select name="" id="" class="city">
<option>--请选择城市--</option>
</select>
<select name="" id="" class="county">
<option>--请选择城市--</option>
</select>
<script>
var data = [
{
value: '吉林省1',
children: [
{
value: '通话市1',
children: [
{
value: 'aa1'
}
]
},
{
value: '白山市1'
}
]
},
{
value: '吉林省2',
children: [
{
value: '通话市2'
},
{
value: '白山市2',
children: [
{
value: 'bb2'
}
]
}
]
},
{
value: '吉林省3',
children: [
{
value: '通话市3'
},
{
value: '白山市3',
children: [
{
value: 'cc2'
}
]
}
]
}
]
var province = document.querySelector('.province')
var city = document.querySelector('.city')
var county = document.querySelector('.county')
data.forEach((val, index) => {
var option = document.createElement('option')
option.value = index
option.innerHTML = val.value
province.appendChild(option)
})
province.onchange = function() {
city.innerHTML = '<option>--请选择城市--</option>'
county.innerHTML = '<option>--请选择城市--</option>'
data[this.value] ? data[this.value] : []
data[this.value].children.forEach((val, index) => {
var option = document.createElement('option')
option.value = index
option.innerHTML = val.value
city.appendChild(option)
})
var that = this
city.onchange = function() {
data[that.value].children[this.value].children =
data[that.value].children[this.value].children || []
data[that.value].children[this.value].children.forEach(
(val, index) => {
var option = document.createElement('option')
option.value = index
option.innerHTML = val.value
county.appendChild(option)
}
)
}
}
</script>
</body>
</html>