今天用js做了一個三級關聯菜單,發現這種東西還是蠻費腦力的,要被這個對象給搞蒙了!以下是我分享出來的代碼,希望對大家有幫助!
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>三級關聯菜單</title>
</head>
<body>
<form action="" name="form1">
<select name='province' οnchange="getCity();">
<option value="">==請選擇省份==</option>
</select>
<select name='city' οnchange='getCountry();'>
<option value="">==請選擇城市==</option>
</select>
<select name="country">
<option value="">==請選擇區域==</option>
</select>
</form>
<script type="text/javascript">
var array=[
{name:'湖南省',cities:[{name:'長沙市',countries:['嶽麓區','天心區','雨花區','望城區']},
{name:'嶽陽市',countries:['平江縣','嶽陽樓','洞庭湖']}
]},
{name:'湖北省',cities:[{name:'武漢市',countries:['武漢區','武岡區','矽谷區','東湖區']},
{name:'武岡市',countries:['黃花區','黃花去1','黃花區12','黃花去12']}
]},
{name:'北京省',cities:[{name:'北京市',countries:['北京1區','北京1區','北京1區','北京1區']},
{name:'北京市',countries:['北京2區','北京2區','北京2區','北京2區']}
]}
]
var province=document.form1.province;
var city=document.form1.city;
var country=document.form1.country;
window.οnlοad=function(){
for(var i=0;i<array.length;i++){
province[i+1]=new Option(array[i].name,array[i].name);
}
}
function getCity(){
var proIndex=province.selectedIndex;
alert(proIndex);
var selectedCity=array[proIndex-1].cities;
for(var i=0;i<selectedCity.length;i++){
city[i+1]=new Option(selectedCity[i].name,selectedCity[i].name);
}
}
function getCountry(){
var proIndex=province.selectedIndex;
var selectedCity=array[proIndex-1].cities;
var cityIndex=city.selectedIndex;
var selectedCountry=selectedCity[cityIndex-1].countries;
for(var i=0;i<selectedCountry.length;i++){
country[i+1]=new Option(selectedCountry[i],selectedCountry[i])
}
}
</script>
</body>
</html>