用原生js写省市级联

来源:互联网 发布:李弘基变脸软件 编辑:程序博客网 时间:2024/05/19 06:35

html代码

<select name="" id="prov">
            <option value="">--请选择省份--</option>
        </select>
        <select name="" id="city">
            <option value="">--请选择市/区--</option>
        </select>

JavaScript代码

<script type="text/javascript">
        var _prov = document.getElementById("prov");
        var _city = document.getElementById("city");
        
        var myCity=new Array();
        myCity['河南省'] = ['郑州市','周口市','新乡市','开封市','洛阳市'];
        myCity['河北省'] = ['石家庄市','衡水市','保定市','邯郸市','张家口市'];
        myCity['北京市'] = ['朝阳区','海淀区','西城区','东城区','房山区'];
        
        for(var i in myCity){
            _prov.add(new Option(i,i),null);    
        }
    
        _prov.onchange = function(){
            var _provV = this.value;
            _city.options.length = 1;
            for(var j in myCity[i]){
            
                switch(_provV){
                    case "河南省":
                    _city.add(new Option(myCity["河南省"][j],j),null);
                    break;
                    case "河北省":
                    _city.add(new Option(myCity["河北省"][j],j),null);    
                    break;
                    case "北京市":
                    _city.add(new Option(myCity["北京市"][j],j),null);    
                    break;
                    
                }
            }
            
        }
    </script>