本文实例为大家分享了JavaScript实现省市联动的具体代码,供大家参考,具体内容如下
实现效果:
2.选择省,后面跟本省对应的市
实现过程:
1.获得省的Dom对象
2.用循环为省的下拉菜单设置option子节点,并将数组每个pName的值赋给创建的子节点
3.每次循环同时为option子节点设置value属性
4.同理在点击省的同时,为市创建option子节点,并将cName的值赋给子节点,设置属性
实现细节:
1. 点击省时采用onchange事件(元素值改变时触发)
2. 每次为市增加节点,要将节点清空,否则市的节点会叠加,可采用option长度为0, citySel.options.length = 0;
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Document</title> <style> .Box{ width: 500px; padding: 20px; border: 1px solid #aaa; margin: 100px auto; } .Box select{ width: 150px; margin: 10px; } </style> <script> var provs = [{"id":"01","pName":"河南省"},{"id":"02","pName":"河北省"},{"id":"03","pName":"四川省"}]; var citys = [{"id":"001","cName":"安阳市","pId":"01"},{"id":"002","cName":"郑州市",{"id":"003","cName":"新乡市",{"id":"004","cName":"邯郸市","pId":"02"},{"id":"005","cName":"石家庄市",{"id":"006","cName":"合肥市",{"id":"007","cName":"广陵市","pId":"03"},{"id":"008","cName":"成都市",{"id":"009","cName":"重庆市","pId":"03"}]; function $(id){ return document.getElementById(id); } window.onload = function (){ var proSel = $('province'); for(var i = 0; i<provs.length; i++){ var Coption = document.createElement('option'); Coption.innerHTML = provs[i].pName; Coption.setAttribute('value',provs[i].id); proSel.appendChild(Coption); } proSel.onchange = function(){ var city =$('city'); var Pid = this.value; city.options.length = 0;//把Select的属性清空 for(var i=0; i<citys.length; i++){ if(Pid == citys[i].pId){ var Noption = document.createElement('option'); Noption.innerHTML = citys[i].cName; Noption.setAttribute('value',citys[i].id); city.appendChild(Noption); } } } } </script> </head> <body> <div class="Box"> 请选择: <select id="province"> <option value="00">----请选择----</option> </select><label for="province">省</label> <select id="city"> <option value="000">----请选择----</option> </select><label for="city">市</label> </div> </body> </html>