JavaScript

超轻量级php框架startmvc

JavaScript实现省市联动效果

更新时间:2020-09-24 06:18:02 作者:startmvc
本文实例为大家分享了JavaScript实现省市联动的具体代码,供大家参考,具体内容如下实现

本文实例为大家分享了JavaScript实现省市联动的具体代码,供大家参考,具体内容如下

实现效果:

1.当点击文字时选中对应的下拉菜单

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":"郑州市","pId":"01"},{"id":"003","cName":"新乡市","pId":"01"},{"id":"004","cName":"邯郸市","pId":"02"},{"id":"005","cName":"石家庄市","pId":"02"},{"id":"006","cName":"合肥市","pId":"02"},{"id":"007","cName":"广陵市","pId":"03"},{"id":"008","cName":"成都市","pId":"03"},{"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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

js 省市联动