JS实现省市二级联动

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>省市二级联动</title>
    <script>
    /*
        找对象,找事件,实现相应的方法
     */
    var sheng = ['请选择','广东省','湖南省','湖北省'];
    var shi = [[],['广州市','深圳市','东莞市'],['长沙','株洲','湘潭'],['武汉市','咸宁市','天门市']];
    function $(id){
        return document.getElementById(id);
    }

    function createsheng(){
        for(var i=0;i < sheng.length;i++){
            var op = new Option(sheng[i],sheng[i]);
            $('sheng').options.add(op);
        }

    }

    function createshi(){
        var shengIndex = $('sheng').selectedIndex;
        $('shi').length = 0;
        for(var i = 0;i < shi[shengIndex].length;i++){
            var op = new Option(shi[shengIndex][i],shi[shengIndex][i]);
            $('shi').options.add(op);
        }
        
    }

    window.onload = function(){
        createsheng();
        $('sheng').onchange = createshi;
    }
    </script>
</head>
<body>
省:<select id="sheng"></select>
市:<select id="shi"></select>
</body>
</html>

效果:

posted @ 2016-02-10 21:43  bybelief  阅读(792)  评论(0编辑  收藏  举报