先来看看最终效果,上图
html
<form id="form" action="?" method="GET">
<select name="province" id="province">
<option value="请选择省">请选择省</option>
</select>
<select name="city" id="city">
<option value="请选择市">请选择市</option>
</select>
<select name="region" id="region">
<option value="请选择区">请选择区</option>
</select>
<button type="submit">提交</button>
</form>
js
推荐思路:
- 默认加载省列表
- 监听change事件,当省选项改变时触发
this.selectedIndex
内置属性,记录着选择省的索引- 将索引传入
showCitys()
,显示对应城市列表
0、获取节点
function $(selector) {
return document.querySelector(selector)
}
function $$(selectors) {
return document.querySelectorAll(selectors)
}
let form = $('#form')
let select = $$('select') //获取所有select标签
let province = $('#province')
let city = $('#city')
let region = $('#region')
let selectIndex = 0 //定义select索引,默认0
let newProvTargetIndex = 0 // 记录所选择省的索引
1、默认加载省列表
function createPanel(data, index) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
let option = document.createElement('option')
option.innerText = data[key].name
select[index].appendChild(option)
}
}
}
showProvinces()
function showProvinces() {
createPanel(provinces, selectIndex)
}
2、监听change事件
province.addEventListener('change', function () { //表单的change事件
showCitys(this.selectedIndex) //传递选择的省的索引作为参数,显示对应城市列表
console.log(this.selectedIndex)
console.log(this.value)
console.log(this.options[this.selectedIndex])
}, false)
function showCitys(index) {
console.log('prov: ', index)
selectIndex = 1
select[selectIndex].options.length = 1 //在省选项改变时触发,重置城市和区
select[selectIndex + 1].options.length = 1
newProvTargetIndex = index
if (index === 0) {
return
}
createPanel(provinces[index - 1].citys, selectIndex) //因为多了~选择省~这一项,要减一
}
另一种写法详见: js三级联动(二)
附加: 好好学习天天向上