一、项目需求
想在网页上显示中国城市列表,而且需要将城市名都存在JS文件中。在网上找了一圈,拿别人的东西改了一下,基本上达到了自己的效果:
二、代码
html代码:
5 | <title>城市选择的三种实现</title> |
6 | <link rel= "stylesheet" href= "style.css" > |
11 | <legend>方法三:按字母顺序选中城市</legend> |
12 | <label for = "addr-show03" >您选择的是: |
13 | <input type= "text" id= "addr-show03" > |
18 | <li value= '1' >ABCD</li> |
19 | <li value= '2' >EFGH</li> |
20 | <li value= '3' >JKLM</li> |
21 | <li value= '4' >NPQR</li> |
22 | <li value= '5' >STWX</li> |
27 | <li value= '10' >YZ</li> |
29 | <div id= "data-show" ></div> |
33 | <script src= "city02.js" ></script> |
34 | <script src= "method01.js" ></script> |
35 | <script src= "method03.js" ></script> |
JS的代码:
1 | var addrShow03 = $( 'addr-show03' ); |
2 | var dataOrder = $( 'data-order' ).querySelectorAll( 'li' ); |
3 | var dataShow = $( 'data-show' ); |
10 | function showHotCity() { |
11 | for ( var i = 0; i < 380; i++) { |
12 | dataOrder[i].className = 'cityOn' ; |
13 | var citysLen = cityAll[i].citys.length; |
14 | var dl = document.createElement( 'dl' ); |
15 | var dt = document.createElement( 'dt' ); |
16 | dt.innerText = cityAll[i].name; |
17 | var dd = document.createElement( 'dd' ); |
22 | for ( var n = 0; n < citysLen; n++) { |
23 | var aCity = document.createElement( 'a' ); |
24 | aCity.innerText = cityAll[i].citys[n]; |
25 | dd.appendChild(aCity); |
27 | dataShow.appendChild(dl); |
三、成果展示:

四、存在问题
JS文件中有一句
1 | var dataOrder = $( 'data-order' ).querySelectorAll( 'li' ); |
是生成一个nodelist的,我直接改成array不行,所以在html那里重复写了很多li元素。
源码:
01省市区三级联动
五、根据省份取城市名称
5 | <title>根据省份选择城市</title> |
6 | <link rel= "stylesheet" href= "style.css" > |
9 | <h2>选择省份之后显示该省下所有城市</h2> |
12 | <h2>选择城市之后显示该城市下所有县区</h2> |
14 | <script src= "city.js" ></script> |
16 | <script type= "text/javascript" > |
19 | function showcityinp(index) { |
20 | var cityLen = provice[index].city.length; |
21 | for ( var j = 0; j < cityLen; j++) { |
22 | var x = provice[index].city[j].name; |
23 | var para = document.createElement( "p" ); |
24 | var node = document.createTextNode(x); |
25 | para.appendChild(node); |
26 | var element = document.getElementById( "div1" ); |
27 | element.appendChild(para); |
35 | function showCountry2(provid,cityid) { |
36 | var cityLen = provice[provid].city.length; |
37 | if (cityid > cityLen) { |
38 | document.write( "cityid超出范围" ) |
40 | var countryLen = provice[provid].city[cityid].districtAndCounty.length; |
41 | for ( var k = 0; k < countryLen; k++) { |
42 | var x = provice[provid].city[cityid].districtAndCounty[k]; |
43 | var para = document.createElement( "p" ); |
44 | var node = document.createTextNode(x); |
45 | para.appendChild(node); |
46 | var element = document.getElementById( "div2" ); |
47 | element.appendChild(para); |
成果展示 :

源码下载:
citylist
可参考网站:https://github.com/visugar/FrontEnd-examples