具体思路:先将一级标签添加到html中,为select添加onchange属性,只要一级框里的内容改变,就会调用linkage来为二级框添加对应的option。两个框之间的联系通过index进行配。因此childData和parentData两个数据的对应情况就变得非常重要。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>表单联动</title>
</head>
<body>
<h1>表单联动</h1>
<form action="">
请选择城市:
<select name="parent" id="parent">
<option value="">请选择</option>
</select>
<br/>
请选择区县:
<select name="child" id="child">
<option value="">请选择</option>
</select>
</form>
<script>
var parent = document.getElementById('parent'),
parentData = [
{code: 0, value: '请选择'},
{code: 1, value: '北京'},
{code: 2, value: '上海'},
{code: 3, value: '深圳'}
],
child = document.getElementById('child'),
childData = [
['请选择'],
['海淀区', '朝阳区', '丰台区', '石景山区', '通州区', '顺义区'],
['黄埔区', '浦东区 ', '长宁区', '宝山区 ', '杨浦区', '嘉定区','虹口区'],
['罗湖区', '福田区 ', '南山区', '保安新区 ', '光明新区']
];
add(parent,parentData,child, childData)
function add(parent,parentData,child, childData){
var num=parentData.length
for(var j=1;j<num;j++){
var opt=document.createElement("option")
opt.innerHTML=parentData[j].value
opt.setAttribute('value',parentData[j].value)
parent.appendChild(opt)
}
}
function linkage(j,elem,Data){
elem.innerHTML=''
var numchilad=Data[j].length
for(var i=0;i<numchilad;i++){
var opt=document.createElement("option")
opt.innerHTML=Data[j][i]
opt.style.value=Data[j][i]
elem.appendChild(opt)
}
}
parent.setAttribute('onchange','linkage(this.selectedIndex,child,childData)')
</script>
</body>
</html>