如何做省份的下拉列表?
1获取select对象 var selProv=getEl("prov");//获取对象
2,遍历select对象 selProv.options[n]=opt;
3,获取省份对象
var prov=new Array(2);
prov["陕西"]=["西安","渭南","咸阳","汉中"];
prov["河南"]=["郑州","洛阳","开封"];
prov["四川"]=["成都","广元"];
4,遍历省份对象
for(var p in prov){
var opt=new Option(p);//创建一个Option对象
selProv.options[n]=opt;
n++;
如何获取市的下拉列表?
1获取select对象 var selCity=getEl("city")
2,遍历select对象 selCity.options[i]=opt;
3,获取市对象 var citys=prov[p];
4,遍历市的对象
for(var i=0;i<citys.length;i++){
var opt=new Option(citys[i]);
selCity.options[i]=opt;
}
全部代码:
<select id="prov" onchange="selCity(this);">
</select>省
<select id="city"></select>市
<script>
var prov=new Array(2);
prov["陕西"]=["西安","渭南","咸阳","汉中"];
prov["河南"]=["郑州","洛阳","开封"];
prov["四川"]=["成都","广元"];
function getEl(id){
return document.getElementById(id);
}
//初始化省份
function initProv(){
var selProv=getEl("prov");//获取对象
var n=0;
for(var p in prov){
var opt=new Option(p);//创建一个Option对象
selProv.options[n]=opt;
n++;
}
selCity(selProv);
}
function selCity(o){
var p=o.value;
var citys=prov[p];
var selCity=getEl("city");//获取HTML对象
//清除
selCity.options.length=0;
for(var i=0;i<citys.length;i++){
var opt=new Option(citys[i]);
selCity.options[i]=opt;
}
}
initProv();
</script>
</body>