涉及特性
- Promise
- Array
filter()
map()
push()
join()
- Spread syntax 扩展语句
- RegExp
效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Type Ahead 👀</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="City or State">
<ul class="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form>
<script>
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
var cities = [];
fetch(endpoint).then(blob => blob.json()).then(data => {
cities.push(...data);
}).catch(err => conosle.error(err));
var input = document.querySelector('.search');
var suggestions = document.querySelector('.suggestions');
input.addEventListener('change', showCitise);
input.addEventListener('keyup', showCitise);
function showCitise(envent) {
let value = envent.target.value;
let peck = cities.filter(city => city.city.match(value) || city.state.match(value));
const items = peck.map(item => {
const cityName = item.city.replace(value, `<span class="hl">${value}</span>`);
const stateName = item.state.replace(value, `<span class="hl">${value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(item.population)}</span>
</li>
`;
}).join('');
suggestions.innerHTML = items;
};
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
</script>
</body>
</html>