js 实现二级联动

Posted klvchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 实现二级联动相关的知识,希望对你有一定的参考价值。

onchange 事件

<body>
    <select id="province" onchange="func1()">
        <option value="shandong">山东</option>
        <option value="hebei">河北</option>
        <option value="beijing">北京</option>
    </select>

</body>
<script>
    function func1(){
        var pro = document.getElementById("province");
        console.log(pro.value)
    }
</script>

使用字典方式添加数据

一级数据显示

<body>
    <select id="province" >
    </select>

</body>
<script>
    data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
    var pro = document.getElementById("province");
    for (var i in data){
        var option_pro = document.createElement("option");
        option_pro.innerhtml=i;
        pro.appendChild(option_pro);
    }
</script>

二级数据联动 方式一

<body>
    <select id="province" onchange="func1(this)" >
    </select>
    <select id="city"></select>
</body>
<script>
    data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
    var pro  = document.getElementById("province");
    var city = document.getElementById("city");

    for (var i in data){
        var option_pro = document.createElement("option");
        option_pro.innerHTML=i;
        pro.appendChild(option_pro);
    }

    function func1(self){
        //console.log((self.options[self.selectedIndex]).innerHTML);
        var choice = (self.options[self.selectedIndex]).innerHTML;

        var options = city.children;
        for (var k=0; k<options.length; k++){
            city.removeChild(options[k--]);
        }

        for (var i in data[choice]){
            var option_city = document.createElement("option");
            option_city.innerHTML = data[choice][i];
            city.appendChild(option_city);
        }
    }
</script>

二级数据联动 方式二

<body>
    <select id="province" onchange="func1(this)" >
    </select>
    <select id="city"></select>
</body>
<script>
    data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
    var pro  = document.getElementById("province");
    var city = document.getElementById("city");


    for (var i in data){
        var option_pro = document.createElement("option");
        option_pro.innerHTML=i;
        pro.appendChild(option_pro);
    }



    function func1(self){
        //console.log((self.options[self.selectedIndex]).innerHTML);
        var choice = (self.options[self.selectedIndex]).innerHTML;

        city.options.length=0;

        for (var i in data[choice]){
            var option_city = document.createElement("option");
            option_city.innerHTML = data[choice][i];
            city.appendChild(option_city);
        }
    }
</script>

以上是关于js 实现二级联动的主要内容,如果未能解决你的问题,请参考以下文章

JS实现省市二级联动

PHP+ajax实现二级联动菜单功能

利用JS实现一个简单的二级联动菜单

phpcms联动菜单有啥用

Ajax 异步请求(登录案例实现 + ajax实现二级联动)

asp 二级联动菜单