基于JQ的三级联动菜单选择

<!-- author:青芒 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三级联动菜单</title>
</head>
<body>
    <select class="one">
        <option value="请选择">请选择</option>
    </select>

    <select class="two">
        <option value="请选择">请选择</option>
    </select>

    <select class="three">
        <option value="请选择">请选择</option>
    </select>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>
        $(function(){
            var oneArr = ["1","2","3"]; //数组1

            var twoArr = [ //数组2
                ["1-1","1-2","1-3"],
                ["2-1","2-2","2-3"],
                ["3-1","3-2","3-3"]
            ];

            var threeArr = [ //数组3
                [
                    ["1-1-1","1-1-2","1-1-3"],["1-2-1","1-2-2","1-2-3"],["1-3-1","1-3-2","1-3-3"]
                ],
                [
                    ["2-1-1","2-1-2","2-1-3"],["2-2-1","2-2-2","2-2-3"],["2-3-1","2-3-2","2-3-3"]
                ],
                [
                    ["3-1-1","3-1-2","3-1-3"],["3-2-1","3-2-2","3-2-3"],["3-3-1","3-3-2","3-3-3"]
                ]
            ];

            let oneHtml = '<option value="请选择">请选择</option>';
            for(let i in oneArr){
                i = Number(i);
                oneHtml += '<option value="'+ i +'">'+ oneArr[i] +'</option>';
            }
            $(".one").html(oneHtml);

            $(".one").change(function(){ //下拉框1选择事件
                if($(this).val() == "请选择"){ //下拉框1如果点击了请选择,则2,3都内容都重置成“请选择”
                    $(".two, .three").html('<option value="请选择">请选择</option>');
                    return;
                }

                let thisVal = Number($(this).val());
                let twoHtml = '';
                for(let j in twoArr[thisVal]){
                    j = Number(j);
                    twoHtml += '<option value="'+ (j+1) +'">'+ twoArr[thisVal][j] +'</option>';
                }
                $(".two").html(twoHtml);

                let threeHtml = '';
                for(let k in threeArr[thisVal][0]){
                    k = Number(k);
                    threeHtml += '<option value="'+ (k+1) +'">'+ threeArr[thisVal][0][k] +'</option>';
                }
                $(".three").html(threeHtml);
            });

            $(".two").change(function(){ //下拉框2选择事件
                let oneVal = Number($(".one").val());
                let thisVal = Number($(this).val()) - 1;

                let threeHtml = '';
                for(let x in threeArr[oneVal][thisVal]){
                    threeHtml += '<option value="'+ (x+1) +'">'+ threeArr[oneVal][thisVal][x] +'</option>';
                }
                $(".three").html(threeHtml);
            });
        })
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/muou2125/p/9212320.html