三级联动(美化版)

话不多说,先上图演示:在这里插入图片描述
数据来源都是网上的那些免费的API地区接口

  1. 先将直辖市和特别行政区进行整合,生成新的数据
  2. 将这些省会渲染出来
  3. 再根据省会渲染出城市
  4. 根据城市渲染地区

没有定位,所以利用随机数,来随机出了省会,再根据省会里面的城市,随机出城市,再根据城市里面的地区,随机出默认的地区

数据整合成直辖市和特别行政区,上代码:

function checkList(list){
     var arr = [],arr1=[];
     for(var i = 0;i<4;i++){
         arr.push(list.shift());
     }
     list = list.filter((item)=>{
         if(item.name == "澳门" || item.name == "香港"){
             arr1.push(item)
             return false;
         }else{
             return true;
         }
     })
     list.unshift({
         "city_id": "CH98",
         "name":"直辖市",
         "en":'',
         "list":arr
     },
     {
         "city_id": "CH99",
         "name":"特别行政区",
         "en":'',
         "list":arr1
     })
     return list;
 }

返回整合后的数据

随机省份以及对应的城市和区域:

function setCity(provinceList,parent){
     parent.textContent = '';
     var nums = Math.round(Math.random()*(provinceList.length-1));
     provinceList.map((item)=>{
         var a = document.createElement("a");
         a.textContent = item.name;
         a.setAttribute("city_id",item.city_id);
         a.addEventListener("click",clickHandler);
         parent.appendChild(a);
     })
     var list = Array.from(parent.children);
     list[nums].setAttribute("class","hovers");
     return provinceList[nums];
 }

以上两个函数就能将基本的样式渲染出来,但是没有点击事件,根据用户点击的省份,改变城市列表中的数据,点击城市,改变区域的数据。

给每个元素都添加点击事件,点击事件如下:

function clickHandler(e){
     var list = Array.from(e.target.parentElement.children);//获取当前父元素下的所有元素
     list.map((item)=>item.setAttribute("class",""));//将元素的样式全部清除,再设置新的样式
     e.target.setAttribute("class","hovers");
     if(e.target.parentElement.id === "cityfirst"){  //判断点击的是省、市、区
         provinceListC = provinceList.filter((item)=>
             item.city_id == e.target.getAttribute("city_id")
         )
         setCity(provinceListC[0].list,city);
     }else if(e.target.parentElement.id === "citysecond"){
         if(!provinceListC[0]){
            provinceListT = provinceListC.list.filter((item)=>
                 item.city_id == e.target.getAttribute("city_id")
             )    
         }else{
             provinceListT = provinceListC[0].list.filter((item)=>
                 item.city_id == e.target.getAttribute("city_id")
             )
         }
         setCity(provinceListT[0].list,town);    
     }else if(e.target.parentElement.id === "cityend"){
         setWeather(e.target.getAttribute("city_id"));
         zswWeather(e.target.getAttribute("city_id"));
         Weather7(e.target.getAttribute("city_id"));
         setLife(e.target.getAttribute("city_id"));
     } 
 }

其他的css样式就不展示了,只是展示了js的实现。欢迎指正。

猜你喜欢

转载自blog.csdn.net/qq_40375518/article/details/106863940
今日推荐