省市二级联动

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>二级联动</title>
<meta charset="UTF-8">
</head>
<body>
<select id="province" onchange="func1(this)">
<option></option>
</select>
<select id="city">
<option></option>

</select>
<script>
data={'河北省':['邯郸','廊坊'],'北京':['海淀','朝阳'],'山东省':['烟台','青岛']};
//方式一:
var provs=document.getElementById('province');
var city=document.getElementById('city');
for(var i in data){
var option_prov=document.createElement('option');
option_prov.innerHTML=i;
provs.appendChild(option_prov);

}

function func1(self){
// alert(self.selectedIndex);//可以得到选择内容的索引
var choice=(self.options[self.selectedIndex]).innerHTML;

var options=city.children;
for(var k=0;k<options.length;k++){
city.removeChild(options[k]);
k--;
}
// city.options.length=0;//与上面for循环功能相同
for(var i in data[choice]){
var option_city=document.createElement('option');
option_city.innerHTML=data[choice][i];
city.appendChild(option_city);


}
}

</script>

</body>
</html>
posted @ 2020-02-06 23:06  Stary_tx  阅读(351)  评论(0编辑  收藏  举报