地市级关联
地市級級聯控件 < 思路:準備好地市級數據,用js dom 操作動態生成select和option標簽,值變化時觸發事件找子節點 河南 河北 鄭州 開封 管城區 >
<script>var info =[{name:'河南',cities:[{name:'鄭州',area:['二七區',//層級太多省略寫了一點,縣區的結構也應該對象'中原區']},{name:'開封',area:['尉氏','通許']}]},{name:'河北',cities:[{name:'石家莊',area:['石家莊區1','石家莊區2','石家莊區3']},{name:'保定',area:['保定區1','保定區2','保定區3']}]}]// (了解)關系型數據中這樣儲存// id name parent_id// 1 河南 0// 2 河北 0// 3 鄭州 1// 4 開封 1// 5 石家莊 2// 6 管城區 3
// 省
var proSel=document.createElement('select');//province select 創建節點
document.body.appendChild( proSel);//<body><select></select></body>// js中大量一種函數:函數套函數,第二個函數就是第一個函數的參數,第一個函數邏輯走完后會把數據交給第二個函數繼續處理。
// callback:回調函數。當外層函數執行完的時候,再執行內層函數// eg:一個人去小賣部買番茄味的方便面(外層函數),老板說
// 賣完了(外層函數無法立即得到結果),我去補貨,你先回家等消息。貨來了(外層函數得到結果)之后我會給你打電話(傳參)。
// 你去小賣部取的方便面,煮了吃了(內層函數執行完)。
// 內層的function(el) 函數看似是個定義,但條件到達時就會執行。
info.forEach(function(el,i){ //[].forEach(function(element,index){})console.log(el,i);var opt= document.createElement('option');//<option></option>opt.textContent=el.name;//<option>河南</option>proSel.appendChild(opt);//<select><option>河南</option></select>
});// 市
var citySel=document.createElement('select');
document.body.appendChild(citySel);
// 先不要考慮事件、option索引、關聯市級select,會導致編碼困難。先寫死部分數據簡化分析。
info[0].cities.forEach(function(el,i){var opt=document.createElement('option');opt.textContent=el.name;citySel.appendChild(opt);
})
// 縣區
var areaSel=document.createElement('select');
document.body.appendChild(areaSel);
info[0].cities[0].area.forEach(function(el,i){//['管城區','高校區']var opt=document.createElement('option');opt.textContent=el; areaSel.appendChild(opt);
})// 動態關聯。
// 先寫死河北省,清空citySel,拼上新option,封裝成函數,動態傳入用戶選擇省的坐標。研究完省到市,再研究市到縣
function refreshArea(){// 根據所選城市,修改縣areaSel.innerHTML='';//數碼分類:<ul>數碼<li>電腦</li><li>手機</li></ul> innerText只標簽內容(不包含更下一級標簽)// 用戶選擇了那個省哪個市 下拉框對象.selectedIndex可以返回選擇項的索引。// 如果迷惑分成多個語句寫 var cities=info[proSel.selectedIndex]info[proSel.selectedIndex].cities [citySel.selectedIndex].area.forEach(function(el,i){var opt=document.createElement('option');opt.textContent=el;areaSel.appendChild(opt);})
}proSel.onchange=function(){// 省變化、修改市citySel.innerHTML='';info[proSel.selectedIndex].cities.forEach(function(el,i){var opt =document.createElement('option');opt.textContent=el.name;citySel.appendChild(opt);});// 市變化后跟著變下縣refreshArea();
}
citySel.onchange=function(){refreshArea();
}</script>
總結
- 上一篇: MATLAB 数据拟合方法
- 下一篇: 开源微信管家平台——JeeWx 捷微4.