使用方法
const endpoint = '../cities.json'; //Array of objects
const cities = [];
fetch(endpoint) //zaciagamy dane z linka
.then(blob => blob.json()) //mówimy, że jest to plik json
.then(data => cities.push(...data)) //wpychamy do tablicy cities jako osobne elementy dlatego są ...
.then(all => displayMatches());
function findMatches(input) {
return cities.filter(place => {
const regex = new RegExp(input, 'gi') //tworzymy wyrażenie regularne którym jest nasz input, czyli to co wpisze szukający drugi to: g - global czyli globalny, i - insensitive (czyli nie zwraca uwagi na wielkość liter)
return place.city.match(regex) || place.state.match(regex); //zwracamy tablicę pasująych do naszego wyrażenia miast lub stanów
});
}
function numberWithCommas(a) {
return a.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');
}
function displayMatches() {
const input = searchInput.value;
const matchArray = findMatches(input);
const htmlMatchArray = matchArray.map(place => {
const regex = new RegExp(input, 'gi');
const cityName = place.city.replace(regex, `<span class="highlight">${input}</span>`);
const stateName = place.state.replace(regex, `<span class="highlight">${input}</span>`);
return `<li>
<p class="city-state"><span class="city">${cityName},</span> ${stateName} <span class="population">population: ${numberWithCommas(place.population)} </span> </p>
</li>`;
}).join('');
const headerText = input ? `${matchArray.length} matches for <span class="input">${input}<span>` : `List of 1000 cities in the USA`;
searchResults.innerHTML = htmlMatchArray;
header.innerHTML = headerText;
}
const searchInput = document.querySelector('#search');
const searchResults = document.querySelector('#search-results');
const header = document.querySelector('h6');
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
站长提示:
1. 苦力吧素材官方QQ群:
950875342
2. 平台上所有素材资源,需注册登录会员方能正常下载。
3. 会员用户积极反馈网站、素材资源BUG或错误问题,每次奖励
2K币。
4. PHP源码类素材,如需协助安装调试,或你有二次开发需求,可联系苦力吧客服。
5. 付费素材资源,需充值后方能下载,如有任何疑问可直接联系苦力吧客服