首次上傳:2017/05/22
利用fetch()來取回json檔案,並透過filter()及RegExp()等語法來製作搜尋即時顯示關聯效果!
[BLOG]
[DEMO]
預設已經有建立了一個城市的.json清單,
先建立一個空的陣列cities並透過fetch來取得json資料存進去。
建立function findMatches(wordToMatch, cities)
裡面建立了一個RegExp用於match來進行字串比對
建立displayMatches()並用addEventListener來監測輸入框的change&keyup,
每次鍵盤輸入時都會觸發displeyMatches()來處理比對,
將比對結果用map來return 組合的HTML的<li>資料,
操作心得待補...
我原先只用過XMLHttpRequest來取資料,關於promise及fetch的操作目前並不熟悉。
參閱:MDN-fetch
正規表達式,這個真的非常複雜...
我有做紀錄的就是參數後面g代表全部, i代表不分大小寫..
參閱:MDN-RegExp
將陣列資料用參數內的字串連接轉為一個字串,
範例中上了join('')來避免map回傳的陣列有,產生。
範例中利用nth-child(odd)與nth-child(even)來抓li的奇偶數
最簡單的小調整,加個.sort()讓搜尋結果進行排序顯示
function displayMatches() {
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
return `<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)}</span>
</li>`;
}).sort().join('');
suggestions.innerHTML = html;
}