標籤:blog option 會議 index 擷取 var width log 聲明
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title></title></head><body> <select style="width: 100px;" id="pre" onchange="chg(this);"> <option value="-1">請選擇</option> </select> <select style="width: 100px;" id="city" onchange="chg2(this)" ;><option value="-1">請選擇</option></select> <select style="width: 100px;" id="area" onchange="chg3(this)"><option value="-1">請選擇</option></select> <select style="width: 100px;" id="way"><option value="-1">請選擇</option></select></body><script> //聲明省 var pres = ["貴州"]; //直接聲明Array //聲明市 var cities = [ ["-請選擇-","貴陽", "遵義", "安順"], ]; var areas = [ [ ["-請選擇-"], ["-請選擇-", "雲岩區", "南明區"], ["-請選擇-", "匯川區", "紅花崗區"], ["-請選擇-", "平壩區", "普定區"], ] ] var wayareas = [ [ ["-請選擇-", "噴水池2", "昌平3"], ["-請選擇-", "海澱2", "海澱3"] ], [ ["-請選擇-"], ["-請選擇-", "上海路", "南京路"], ["-請選擇-",, "丁字口", "遵義會議"] ], [ ["-請選擇-"], ["-請選擇-",, "濟南2"], ["-請選擇-",, "青島2"] ] ] //設定一個省的公用下標 var pIndex = -1; var preEle = document.getElementById("pre"); var cityEle = document.getElementById("city"); var areaEle = document.getElementById("area"); var wayEle = document.getElementById("way"); //先設定省的值 for (var i = 0; i < pres.length; i++) { //聲明option.<option value="pres[i]">Pres[i]</option> var op = new Option(pres[i], i); //添加 preEle.options.add(op); } function chg(obj) { if (obj.value == -1) { cityEle.options.length = 0; areaEle.options.length = 0; } //擷取值 var val = obj.value; pIndex = obj.value; //擷取ctiry var cs = cities[val]; //擷取預設區 var as = areas[val][0]; //先清空市 cityEle.options.length = 0; areaEle.options.length = 0; wayEle.options.length = 0; for (var i = 0; i < cs.length; i++) { var op = new Option(cs[i], i); cityEle.options.add(op); } for (var i = 0; i < as.length; i++) { var op = new Option(as[i], i); areaEle.options.add(op); } } function chg2(obj) { var val = obj.selectedIndex; var as = areas[pIndex][val]; areaEle.options.length = 0; for (var i = 0; i < as.length; i++) { var op = new Option(as[i], i); areaEle.options.add(op); } } function chg3(obj) { var val = obj.selectedIndex; var as = wayareas[pIndex][val]; wayEle.options.length = 0; for (var i = 0; i < as.length; i++) { var op = new Option(as[i], i); wayEle.options.add(op); } }</script></html>
js 四級聯動