type ahead
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = []; // 데이타값을 받음
fetch(endpoint)
.then(blob => blob.json()) // 제이슨
.then(data => cities.push(...data)); // 데이터
//json 내용 가져오기
// fetch -> 클라이언트가 서버레 어떤파일을 응답해달라고 요청한것
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 searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);fetch()

.push

findMatches()
사용자 입력한 단어로 결과값 찾기

Last updated