js html select 二级菜单

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>select二级下拉菜单</title>
</head>
<script>
    var cityArr = [];
    cityArr['江苏省'] =
            [
                {txt:'南京', val:'南京'},
                {txt:'无锡', val:'无锡'},
                {txt:'徐州', val:'徐州'},
                {txt:'苏州', val:'苏州'},
                {txt:'南通', val:'南通'},
                {txt:'淮阴', val:'淮阴'},
                {txt:'扬州', val:'扬州'},
                {txt:'镇江', val:'镇江'},
                {txt:'常州', val:'常州'}
            ];
    cityArr['浙江省'] =
            [
                {txt:'杭州', val:'杭州'},
                {txt:'宁波', val:'宁波'},
                {txt:'温州', val:'温州'},
                {txt:'湖州', val:'湖州'}
            ];

    function setSelectOption(selectObj, optionList, firstOption, selected) {

    }

    function setCity(province) {
        console.log(province);
        //setSelectOption('city', cityArr[province], '-请选择-');
        var city = document.getElementById('city');
        var city_len = city.options.length;
        console.log(city_len);
        for(var i = 0; i < city_len; i++) {
            if(city_len > 0) {
                city.options.remove(0);
            }
        }

        if(province == "0") {
            var opt = new Option('-请选择-', 0);
            city.options.add(opt);
        }
        else {
            var province_len = cityArr[province].length;
            for(i = 0;i< province_len; i++) {
                var opt = new Option(cityArr[province][i].txt, cityArr[province][i].val);
                city.options.add(opt);
            }
        }
    }
</script>
<body>
<form id="form2" name="diqu" method="post" action="">
    <select name="province" id="province" onchange="
        if(this.value != '')
            setCity(this.options[this.selectedIndex].value);">
        <option value="0">-请选择-</option>
        <option value="江苏省">江苏省</option>
        <option value="浙江省">浙江省</option>
    </select>
    <select name="city" id="city">
        <option value="0">-请选择-</option>
    </select>
</form>
</body>
</html>

  

posted on 2015-08-24 13:22  嘘寒问暖  阅读(1795)  评论(0编辑  收藏  举报

导航