用JavaScript实现二级联动

来源:互联网 发布:修真的电脑程序员 编辑:程序博客网 时间:2024/05/21 10:16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>


<body>
<form  action="" method="get">
    <select name="" id="sheng">
        <option>选择省</option>
        </select>
        <select name="" id="diqu">
        <option>选择地区</option>
        </select>
    </form>

    

<!--JavaScript代码-->


    <script type="text/javascript">
var region = ['全国',['北京市','西城区','东城区','朝阳区'],['上海市','虹桥区','闸北区','浦东区'],
['河北省','石家庄市','沧州市','廊坊市']];

    window.onload = function(){
var sels = document.getElementById("sheng");
var seld = document.getElementById("diqu");

function init(){
for(var i=1;i<region.length;i++){
var opt = document.createElement("option");
var txt = document.createTextNode(region[i][0]);
opt.appendChild(txt);
sels.appendChild(opt);
}

}


function onChange(){
var aRemove = seld.getElementsByTagName("option");
for(var j = aRemove.length - 1;j>0;j--){
seld.removeChild(aRemove[j]);
}

if(this.selectedIndex){
for(var i =1;i<region[this.selectedIndex].length;i++){
var opt = document.createElement("option");
       var txt = document.createTextNode(region[this.selectedIndex][i]);
opt.appendChild(txt);
seld.appendChild(opt);
}
}

}

init();
sels.onchange = onChange;
 

}
    
    
    </script>
</body>
</html>
0 0