需求:用JS實現一個下拉選單,要求在選中“地區”選單中相應的地區時,自動在“國家”選單中 出現相應的國家。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>聯動菜單</title>
</head>
<body>
<p>地區:
<select id="area" οnchange="change();">
<option value="">請選擇</option>
<option value="1">亞洲</option>
<option value="2">歐洲</option>
<option value="3">非洲</option>
</select>
</p>
<p>國家:
<select id="country">
<option>請選擇</option>
</select>
</p>
</body>
<script type="text/javascript" src="select.js" ></script>
</html>
select.js
//假設接收到服務器傳來的參數
var data = [
["中國","朝鮮","日本"],
["挪威","冰島","葡萄牙"],
["南非","津巴布韋","烏干達"]
]
function change(){
var area = document.getElementById("area");
var countrys = document.getElementById("country");
var index = area.value;
var selects = data[index-1]; //通過選中下拉的選單value值獲取數據
var oldOptions = countrys.children; //用children,數組內不會有多餘屬性(換行符)
var length = oldOptions.length; //!!注意,提前記錄length原因:
//如果在遍歷刪除過程中記錄length,則length值會改變,刪除會出錯。
for(var i=0;i<length;i++){ //刪除原先選項的過程,若不刪除,選項會一直堆積。
countrys.removeChild(oldOptions[0]);//一直第一個元素,因爲清除第一個以後,後面的元素會前移。如果按正常的i遍歷,會出錯!
}
if(index==0) return; //如果選中的是"請選擇",就不再添加數據,避免報錯(因爲腳標是-1)
for(var i=0;i<selects.length;i++){ //增加選項過程
var option = document.createElement("option");
option.innerHTML = selects[i];
country.appendChild(option);
}
}