使用javascript实现省市联动的效果如下:
html代码很简单,主要是javascript代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
body{
padding-top:200px;
text-align:center;
}
</style>
</head>
<body >
<select id="pro">
</select>
<select id="city">
</select>
</body>
</html>
javascript代码:
<script>
var provinces=["北京市","上海市","河南省"];
var cities=[];
cities[0]=["东城区","西城区","海淀区","香山区"];
cities[1]=["浦东新区","黄浦区","虹口区","徐汇区","闵行区"];
cities[2]=["商丘市","郑州市","新乡市","南阳市","鹤壁市","许昌市","漯河市"];
function changeSub(){
//先移除掉原来的城市再附加
var city=document.getElementById("city");
var options=city.getElementsByTagName("option");
// console.log( options);
var len=options.length;
for(var i=len-1;i>=0;i--){//注意:不要使用从前往后删除,索引改变for(var i=0;i<len;i++){
console.log("len:"+len);
console.log(options[i]);
console.log(options.length);
city.removeChild(options[i]);
}
var crtPro=this.value;//得到当前选中的省份
var crtCity=cities[parseInt(crtPro)];
for(var i=0;i<crtCity.length;i++){
var newItem=document.createElement("option");
var textnode=document.createTextNode(crtCity[i]);
newItem.appendChild(textnode);
newItem.setAttribute("value",i);
if(i==0){
newItem.setAttribute("selected","selected");
}
city.appendChild(newItem);
}
}
window.onload=function(){
//初始化省份
for(var i=0;i<provinces.length;i++){
var newItem=document.createElement("option");
var textnode=document.createTextNode(provinces[i]);
newItem.appendChild(textnode);
newItem.setAttribute("value",i);
if(i==0){
newItem.setAttribute("selected","selected");
}
var pro=document.getElementById("pro");
pro.onchange=changeSub;//处理省份改变事件
pro.appendChild(newItem);
}
//初始化第一个省份的城市
for(var i=0;i<cities[0].length;i++){
var newItem=document.createElement("option");
var textnode=document.createTextNode(cities[0][i]);
newItem.appendChild(textnode);
newItem.setAttribute("value",i);
if(i==0){
newItem.setAttribute("selected","selected");
}
var city=document.getElementById("city");
city.appendChild(newItem);
}
}
</script>