下拉列表:二級聯動菜單

Select對象的經常使用屬性javascript

options[]:返回全部option組成的一個數組;html

name:名稱java

valueoptionvalue的值數組

length:設置或讀取option的個數post

selectedIndex:當前選中的option的索引號this

option對象的經常使用屬性spa

text:指<option></option>中的文本code

value:指option對象的value屬性orm

index:指每一個option對象的索引號htm

selected:當前option是否選中


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>form表單之select操做</title>
<script type="text/javascript">
var arr_province = ["請選擇省/城市","北京市","上海市","天津市","重慶市","深圳市","廣東省","河南省"];
var arr_city = [
                ["請選擇城市/地區"],
                ["東城區","西城區","朝陽區","宣武區","昌平區","大興區","豐臺區","海淀區"],
                ['寶山區','長寧區','豐賢區', '虹口區','黃浦區','青浦區','南匯區','徐彙區','盧灣區'],
                ['和平區', '河西區', '南開區', '河北區', '河東區', '紅橋區', '塘古區', '開發區'],
                ['俞中區', '南岸區', '江北區', '沙坪壩區', '九龍坡區', '渝北區', '大渡口區', '北碚區'],
                ['福田區', '羅湖區', '鹽田區', '寶安區', '龍崗區', '南山區', '深圳周邊'],
                ['廣州市','惠州市','汕頭市','珠海市','佛山市','中山市','東莞市'],
                ['鄭州市']
            ];

onload = function() {
    var oForm = document.getElementById('form1');
    var oProvince = oForm.children[0];
    var oCity = oForm.children[1];

    // 添加點擊 onchange 事件
    oProvince.onchange = function() {
        var _this = this.selectedIndex;
        // 默認進來高度清零
        oCity.length = 0;
        // 指定城市下拉的高度
        initCity(_this);
    };

    // 初始化下拉列表
    init();
    // init select
    function init(){
        var index = 0;
        // 指定下拉的高度
        oProvince.length = arr_province.length;

        // 循環數組, 把內容寫到下拉列表中去
        for( var i = 0; i < arr_province.length; i++ ){
            oProvince.options[i].text = arr_province[i];
            oProvince.options[i].value = arr_province[i];
        }

        // 指定默認索引號
        oProvince.selectedIndex = index;
        // 指定城市下拉的高度
        initCity(index);
    }

    // 城市下拉內容高度
    function initCity(index){
        // 指定城市下拉的高度
        oCity.length = arr_city[index].length;

        // 循環數組, 把內容寫到下拉列表中去
        for( var i = 0; i < arr_city[index].length; i++ ){
            oCity.options[i].text = arr_city[index][i];
            oCity.options[i].value = arr_city[index][i];
        }
    }

};


</script>
</head>

<body>
<form id="form1">
    省份: <select name="province" style="width:130px;"></select>

    城市: <select name="city" style="width:130px;"></select>
</form>
</body>
</html>