级联下拉列表

 

下拉列表,同步

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            var provinces = ["安徽","江苏","浙江","山东"];
            var cities = [["合肥","芜湖","蚌埠","安庆"],["南京","苏州","无锡","徐州"],["杭州","宁波","温州","金华"],["济南","青岛","烟台","日照"]];

            var provSelNode;
            var citySelNode;

            function initSelect(){
                //初始化省份和城市下拉菜单

                provSelNode = document.getElementById("prov");
                citySelNode = document.getElementById("city");

                //1.初始化省份下拉菜单
                for(var i=0;i<provinces.length;i++){
                    //<option value="xx">provinces[i]</option>

                    //通用的dom操作
                    /*
                    var txtNode = document.createTextNode(provinces[i]);
                    var optNode = document.createElement("option");
                    optNode.value = "";
                    optNode.appendChild(txtNode);
                    provSelNode.appendChild(optNode);
                    */

                    //更简洁的操作
                    var optNode = new Option(provinces[i],"");
                    provSelNode.appendChild(optNode);
                }

                //2.初始化城市下拉菜单
                for(var i=0;i<cities[0].length;i++){

                    var optNode = new Option(cities[0][i],"");
                    citySelNode.appendChild(optNode);
                }
            }
            function updateCitySel(){
                //清空城市下拉菜单
                citySelNode.options.length = 0;

                //更新城市下拉菜单
                var index = provSelNode.selectedIndex;
                for(var i=0;i<cities[index].length;i++){
                    var optNode = new Option(cities[index][i],"");
                    citySelNode.appendChild(optNode);
                }
            }
        </script>
    </head>
    <body onload="initSelect();">
        省份:<select id="prov" onchange="updateCitySel();"></select>&nbsp;&nbsp;&nbsp;&nbsp;
        城市:<select id="city"></select>&nbsp;&nbsp;&nbsp;&nbsp;

    </body>
</html>

这里写图片描述

posted @ 2018-06-01 13:11  hunterxing  阅读(781)  评论(0编辑  收藏  举报