學習筆記-JS30-Day6-Ajax Type Ahead

vincentxu
4 min readMar 22, 2023

--

今日重點:

輸入特定的城市名片段後會出現 json 檔中符合該名字的城市

程式碼:github
線上看:Demo

學習筆記:

關鍵

1. 透過ajax取得城市資料

2. 取得元素的控制權

3. 監聽元素

4. 改變顯示內容

透過Ajax取得城市資料

const cities = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data));

取得元素的控制權

const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

監聽元素

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);

改變顯示內容

//找到符合的內容
function findMatches(wordToMatch, cities) {
return cities.filter((place) => {
const regex = new RegExp(wordToMatch, "gi");
return place.city.match(regex) || place.state.match(regex);
});
}

//顯示符合的內容

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

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>
`;
})
.join("");
suggestions.innerHTML = html;
}

看到不同的做法提供大家參考

// 作法一
const cities = [];
fetch(endpoint)
.then((blob) => blob.json())
.then((data) => cities.push(...data));
// 作法二
let cities = [];
fetch(endpoint)
.then((blob) => blob.json())
.then((data) => cities = data);

// 作法一
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 作法二 原先的population是字串,*1之後就是數字,再轉換加逗號
function numberWithCommas(x) {
return (x * 1) .toLocalString();
}

提供我的github可以參考不同的做法

關於正規表達式(正規表示式/正則表達式/正則運算…超多種用法)
英文是Regular Expression,實在是太艱澀難懂,找了一個影片跟練習網站之後要安排時間來鑽研。

練習網站:RegexOne

練習網站:ihateregex

練習網站:regexr

YT影片:深入淺出正則表達式

--

--

vincentxu
vincentxu

Written by vincentxu

熱愛學習、戶外運動,關心教育,曾任公部門主計,教育工作者/軟體工程師_嘗試將科技與使用者經驗設計導入教育_共同創辦一個線上教育平台,推廣自主學習與民主教育https://www.daoedu.tw/

No responses yet