Case: js secondary linkage

This is a common function of js, such as the linkage of provinces and cities

This is the page tag

   <form action="">
        省份:<select id="pre"></select>
        城市:<select id="cy"></select>
    </form>

This is the data

 var provinces = ["请选择省份", "北京市", "天津市", "上海市", "重庆市", "江苏省", "浙江省", "江西省", "海南省"];
        var citys = [
            ["请选择城市"],
            ["北京市"],
            ["天津市"],
            ["上海市"],
            ["重庆市"],
            ["南京市", "无锡市", "徐州市", "常州市", "苏州市", "南通市", "连云港市", "淮安市", "盐城市", "扬州市", "镇江市", "泰州市", "宿迁市"],
            ["杭州市", "宁波市", "温州市", "绍兴市", "湖州市", "嘉兴市", "金华市", "衢州市", "台州市", "丽水市", "舟山"],
            ["南昌市", "九江市", "上饶市", "抚州市", "宜春市", "吉安市", "赣州市", "景德镇", "萍乡市", "新余市", "鹰潭市"],
            ["海口市", "三亚市", "三沙市", "儋州市"]
        ];

Get element

 		var pre = document.getElementById('pre')
        var cy = document.getElementById('cy')

Render province list

 for (var i = 0; i < provinces.length; i++) {
    
    
 	//创建下拉列表
            var option = document.createElement('option')
            option.innerHTML = provinces[i]//将省份写入列表
            option.value = provinces[i]
            pre.appendChild(option)
        }

Give the initial effect to the secondary list

  var index = 0
        var option = document.createElement('option')
        option.innerHTML = citys[index]
        cy.appendChild(option)

Key code

	pre.onchange = function () {
    
    //省份列表改变时触发
            cy.length = 0//清空二级列表的内容
            for (var k in citys[this.selectedIndex]) {
    
    //遍历当前省份对应的城市数据
                var option = document.createElement('option')
                option.innerHTML = citys[this.selectedIndex][k]
                option.value = citys[this.selectedIndex][k]
                cy.appendChild(option)
            }

        }

Guess you like

Origin blog.csdn.net/weixin_48549175/article/details/111936768