<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; } .tatle{width: 300px;height: 50px;backgroun ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
}
.tatle{width: 300px;height: 50px;background: #ccc;}
.show{width: 300px;height: 400px;border:1px solid #ccc;overflow: scroll;}
.tatle span{
display: inline-block;
width:20px;height: 20px;line-height: 20px;text-align: center;
}
h4{
width: 70px;
float:left;
}
.hot{
width: 300px;
height: 50px;border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="hot" class="hot"></div>
<div id="tatle" class="tatle"></div>
<div id="show" class="show"></div>
<script>
function $(id){
return document.getElementById(id);
}
var tat=$("tatle");
var show=$("show");
var hot=$("hot");
var spans=tat.getElementsByTagName("span");
for(var i=65;i<=90;i++){ //字母對應碼值迴圈
var spant= document.createElement("span");//創建節點放字母
spant.innerHTML=String.fromCharCode(i);//碼值轉字元顯示
tat.appendChild(spant);//節點插入tat
}
try{var http=new XMLHttpRequest;}
catch(e){http=new ActiveXObject("Microsoft.XMLHTTP");}
http.open("GET","city.json",true);//伺服器與JSON文件建立連接
http.send();//發送請求
http.onreadystatechange=function(){
//存儲函數 每當readyState屬性改變時就會調用
if(this.readyState==4 && this.status==200){//判斷是否完成響應且正常
var p=JSON.parse(this.responseText);//字元串轉為對象賦值給p
for(var r=0;r<p.hotList.length;r++){//熱門城市遍歷輸出
hot.innerHTML+="<h4>"+p.hotList[r][0]+"<h4>";
}
}
for(var j=0;j<spans.length;j++){//裝字母的容器遍歷
spans[j].onclick=function(){//點擊字母
show.innerHTML="";
for(var i=0;i<p.cityList.length;i++){
if(p.cityList[i][1].charAt(0).toUpperCase()==this.innerHTML){
//獲取cityList[i][1]的首字母轉大寫
show.innerHTML+="<p>"+p.cityList[i][0]+"</p>";//顯示其對應城市
}
}
}
}
var hotcity=hot.getElementsByTagName("h4");
for(var y=0;y<hotcity.length;y++){
//遍歷熱門城市的容器
hotcity[y].onclick=function(){
show.innerHTML="";
for(var i=0;i<p.cityList.length;i++){
if(p.cityList[i][0].substr(0,2)==this.innerHTML.substr(0,2)){
//獲取熱門城市名,前兩個字匹配
//substr(start,length) start:抽取的子串的起始下標,length:子串中的字元數
show.innerHTML+="<p>"+p.cityList[i][0]+"</p>";
//顯示其匹配結果一樣的站點
}
}
}
}
}
</script>
</body>
</html>
JSON文件:(部分省略)
{
"cityList":[
["北京東","beijingdong","bjd",1],
["北京","beijing","bj",15],
["北京南","beijingnan","bjn",3],
["北京西","beijingxi","bjx",4],
["廣州南","guangzhounan","gzn",5],
["重慶北","chongqingbei","cqb",6],
["重慶","chongqing","cq"],
["重慶南","chongqingnan","cqn"],
["廣州東","guangzhoudong","gzd"],
["上海","shanghai","sh"],
["上海南","shanghainan","shn"],
["上海虹橋","shanghaihongqiao","shhq"],
["上海西","shanghaixi","shx"],
]
"hotList":[
["北京","beijing","bj"],
["上海","shanghai","sh"],
["廣州","guangzhou","gz"],
["長沙","changsha","cs"],
["石家莊","shijiazhuang","sjz"],
["南京","nanjing","nj"],
["鄭州","zhengzhou","zz"],
["深圳","shenzhen", "sz"]
]
}