欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

前端开发之js基础(3)

程序员文章站 2022-06-30 19:15:28
...

js实现京东配送区域列表选择

html代码

<body>
        <div id="main">
            <select id="selectparent" onchange="run(this.value)">
                <option>请选择</option>
                <option value="北京">北京</option>
                <option value="成都">成都</option>
                <option value="河北">河北</option>
                <option value="日本">日本</option>
            </select>
            <select id="selectchild">
            </select>
        </div>
    </body>

js代码

<script type="text/javascript">
        var arr = [];
        arr[0] = new Array("北京","海定区","朝阳区","昌平区","顺义区","大兴区","东城区","西城区");
        arr[1] = new Array("成都","高新区","武侯区","郫都区","青羊区","金牛区","温江区","双流区");
        arr[2] = new Array("河北","石家庄","保定","邯郸","衡水","张家口","唐山","秦皇岛");
        arr[3] = new Array("日本","大阪","东京","神户","长崎","广岛");

        function run(val){
            //获取子节点
            var child = document.getElementById("selectchild");
            var options = child.getElementsByTagName("option");
            //每次选择时清除上次的所有子节点
            for(var i=0;i<options.length;i++){
                child.removeChild(options[i]);
                i--;
            }
            //遍历数组
            for(var j=0;j<arr.length;j++){
                var a = arr[j];
                var b = a[0];
                if(b==val){
                    for(var k=1;k<a.length;k++){
                        var str = a[k];
                        //创建文本节点和标签节点
                        var textchild = document.createTextNode(str);
                        var optionchild = document.createElement("option");
                        //把文本添加到标签内
                        optionchild.appendChild(textchild);
                        child.appendChild(optionchild);
                    }
                }
            }
        }
    </script>