JavaScript 实现二级联动

来源:互联网 发布:你怎么看待网络暴力 编辑:程序博客网 时间:2024/04/30 10:29

效果图:



示例的代码:

<!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="post">
<select name="" id="sheng">
    <option>选择省</option>
    </select>
    <select name="" id="diqu">
    <option>选择地区</option>
    </select>
</form>
<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(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;

}//end



</script>
</body>
</html>

0 0