JavaScript学习第一堂课后续--①输入判断②省市联动
try 可以设置提醒,用catch来捕获返回值
②省市联动
循环填充的时候要先清空之前的,
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
var arr = ["中国","美国","日本"];
arr["中国"] = ["北京","上海","广州","深圳"];
arr["美国"] = ["纽约","华盛顿","洛杉矶","芝加哥"];
arr["日本"] = ["东京","大阪","北海道"];
arr["北京"] = ["北京1","北京2","北京3","北京4"];
arr["上海"] = ["上海1","上海2","上海3","上海4"];
arr["广州"] = ["广州1","广州2","广州3","广州4"];
arr["深圳"] = ["深圳1","深圳2","深圳3","深圳4"];
arr["纽约"] = ["纽约1","纽约2","纽约3","纽约4"];
arr["华盛顿"] = ["华盛顿1","华盛顿2","华盛顿3","华盛顿4"];
arr["洛杉矶"] = ["洛杉矶1","洛杉矶2","洛杉矶3","洛杉矶4"];
arr["芝加哥"] = ["芝加哥1","芝加哥2","芝加哥3","芝加哥4"];
arr["东京"] = ["东京1","东京2","东京3","东京4"];
arr["大阪"] = ["大阪1","大阪2","大阪3","大阪4"];
arr["北海道"] = ["北海道1","北海道2","北海道3","北海道4"];
function addData(arrData,itemID){
document.getElementById(itemID).length = 0;//先清空传过来id的所有内容,再添加
for(var i = 0; i<arrData.length; i++){
var option = new Option();//O大写,
option.text = arrData[i];//返回前台界面值
option.value = arrData[i];//返回数据库值
document.getElementById(itemID).options.add(option);//options固定赋值方法
}
}
function fun(){
addData(arr,"country");
addData(arr[arr[0]],"province");
addData(arr[arr[arr[0]][0]],"area");
}
function changePro(country){
addData(arr[country],"province");
addData(arr[arr[country][0]],"area");//触发地区,也显示城市对应的地区
}
function changeArea(province){
addData(arr[province],"area");
}
</script>
</head>
<body onload="fun()">
国家:<select id="country" onchange="changePro(this.value)"></select>
城市:<select id="province" onchange="changeArea(this.value)" ></select>
地区:<select id="area"></select>
</body>
</html>