数组模拟三级联动

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>三级联动</title>
</head>
<body>
    省:<select id="sel1"></select>
    市:<select id="sel2"></select>
    区:<select id="sel3"></select>
</body>
<script type="text/javascript">
    var arr=[
    '山东',[
    '泰安',['岱岳','泰山','高新'],
    '淄博',['周村','张店','临淄']
    ],
    '北京',[
    '朝阳',['岱岳1','泰山1','高新1'],
    '海淀',['周村1','张店1','临淄1']
    ],
    '山西',[
    '太原',['岱岳2','泰山2','高新2'],
    '运城',['周村2','张店2','临淄2']
    ]
    ];
    var sel1=document.querySelector('#sel1');
    var sel2=document.querySelector('#sel2');
    var sel3=document.querySelector('#sel3');
    for(var i=0;i<arr.length;i++){
        if(typeof arr[i]=='string'){
            sel1.add(new Option(arr[i],arr[i]));
        }
    }
    sel1.onchange=function(){
        for(var i=0;i<arr.length;i++){
        if(typeof arr[i]=='string'){
            if(sel1.value==arr[i]){
                var brr=arr[i+1];
                sel2.innerHTML=''
                for(var j=0;j<arr.length;j++){
                if(typeof brr[j]=='string'){
                    sel2.add(new Option(brr[j],brr[j]));
                }
            }
          }
        }
    }
    }
    sel2.onchange=function(){
        for(var i=0;i<arr.length;i++){
            if (typeof arr[i]!='string') {
                var brr=arr[i];
                for(var j=0;j<brr.length;j++){
                    if(typeof brr[j]=='string'){
                            if(brr[j]==sel2.value){
                                var crr=brr[j+1]
                                sel3.innerHTML=''
                                for(var k=0;k<crr.length;k++){
                                    sel3.add(new Option(crr[k],crr[k]  ));
                                }
                            }
                    }
                }
            }
        }
    }
</script>
</html>
上一篇:HTML添加断点


下一篇:博客园文章版权声明(js自动生成)