一、项目需求
想在网页上显示中国城市列表,而且需要将城市名都存在JS文件中。在网上找了一圈,拿别人的东西改了一下,基本上达到了自己的效果:
二、代码
html代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>城市选择的三种实现</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <fieldset> <legend>方法三:按字母顺序选中城市</legend> <label for="addr-show03">您选择的是: <input type="text" id="addr-show03"> </label> <div id="data-wrap"> <ul id="data-order"> <li value='0'>热门</li> <li value='1'>ABCD</li> <li value='2'>EFGH</li> <li value='3'>JKLM</li> <li value='4'>NPQR</li> <li value='5'>STWX</li> <li value='6'>YZ</li> <li value='7'>YZ</li> <li value='8'>YZ</li> <li value='9'>YZ</li> <li value='10'>YZ</li> </ul> <div id="data-show"></div> </div> </fieldset> </div> <script src="city02.js"></script> <script src="method01.js"></script> <script src="method03.js"></script> </body> </html>
JS的代码:
var addrShow03 = $('addr-show03'); var dataOrder = $('data-order').querySelectorAll('li'); var dataShow = $('data-show'); (function init() { showHotCity(); })(); /*自动加载所有城市*/ function showHotCity() { for (var i = 0; i < 380; i++) { dataOrder[i].className = 'cityOn'; var citysLen = cityAll[i].citys.length; var dl = document.createElement('dl'); var dt = document.createElement('dt'); dt.innerText = cityAll[i].name; var dd = document.createElement('dd'); dl.appendChild(dt); dl.appendChild(dd); for (var n = 0; n < citysLen; n++) { var aCity = document.createElement('a'); aCity.innerText = cityAll[i].citys[n]; dd.appendChild(aCity); } dataShow.appendChild(dl); } }
三、成果展示:
四、存在问题
JS文件中有一句
var dataOrder = $('data-order').querySelectorAll('li');
是生成一个nodelist的,我直接改成array不行,所以在html那里重复写了很多li元素。
源码:
五、根据省份取城市名称
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>根据省份选择城市</title> <link rel="stylesheet" href="style.css"> </head> <body> <h2>选择省份之后显示该省下所有城市</h2> <div id="div1"></div> <hr> <h2>选择城市之后显示该城市下所有县区</h2> <div id="div2"></div> <script src="city.js"></script> <script type="text/javascript"> /*选择省份之后显示该省下所有城市,index应该为数值*/ function showcityinp(index) { var cityLen = provice[index].city.length; for (var j = 0; j < cityLen; j++) { var x = provice[index].city[j].name; var para = document.createElement("p"); var node = document.createTextNode(x); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); } } showcityinp(4) /*选择城市之后显示该城市下所有县区*/ function showCountry2(provid,cityid) { var cityLen = provice[provid].city.length; if (cityid > cityLen) { document.write("cityid超出范围") }else { var countryLen = provice[provid].city[cityid].districtAndCounty.length; for (var k = 0; k < countryLen; k++) { var x = provice[provid].city[cityid].districtAndCounty[k]; var para = document.createElement("p"); var node = document.createTextNode(x); para.appendChild(node); var element = document.getElementById("div2"); element.appendChild(para); } } } showCountry2(4,3) </script> </body> </html>
成果展示 :
源码下载:
citylist
可参考网站:https://github.com/visugar/FrontEnd-examples