<pre>
<!DOCTYPE html>
<html>
<head>
<title>二級聯(lián)動.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
//json對象
// 相當于java當中的map
/*
var json = {"name":"tom","age":18};
//遍歷json對象的鍵
for(var key in json){
//alert(key);
alert(key+"==>"+json[key])
}
*/
//---------------------------------------------------------
var json = {"河北省":["石家莊","廊坊","滄州"],
"山西省":["太原","大同","運城"],
"黑龍江省":["哈爾濱","齊齊哈爾","佳木斯"]};
// 初始化省的下拉選
function fun1(){
//1 獲得省的select對象
var province = document.getElementById("province");
//2 遍歷json的所有鍵
for(var key in json){
// 創(chuàng)建一個option
var option = document.createElement("option");
option.innerHTML = key; // <option>河北省</option>
// 將option添加到select中
province.appendChild(option);
}
}
function fun2(){
//1 獲得市的select對象
var province = document.getElementById("province");
var city = document.getElementById("city");
//2 清空市級下拉選的數(shù)據(jù)
city.length =1;
//3 獲得用戶選擇的省
if(province.selectedIndex==0){
//用戶選擇的是提示選項=>什么也不做
return;
}
//獲取省的集合
var options = province.options;
//獲取選中省的索引province.selectedIndex
var pName = options[province.selectedIndex].innerHTML;
//4 從json中根據(jù)省獲得 省下的市數(shù)據(jù)
var cities = json[pName];
//5 遍歷市級的數(shù)組
for(var i = 0 ; i<cities.length;i++){
var cityName = cities[i];
//創(chuàng)建市的option
var option = document.createElement("option");
option.innerHTML = cityName;
// 將option添加到select中
city.appendChild(option);
}
}
</script>
</head>
<body onload="fun1();">
<select id="province" onchange="fun2();" >
<option>---請選擇省---</option>
</select>
<select id="city" >
<option>---請選擇市---</option>
</select>
</body>
</html>
</pre>