繼續加油。
const panels = document.querySelectorAll('.panel');
function toggleOpen() {
this.classList.toggle('open');
}
function toggleOpenActive(e) {
console.log(e.propertyName);
if(e.propertyName.includes('flex')){
this.classList.toggle('open-active');
}
}
panels.forEach(panel => panel.addEventListener('click',toggleOpen));
panels.forEach(panel => panel.addEventListener('transitionend',toggleOpenActive));
2.06-Ajax Type Ahead
這張是目前覺得自己最不會的地方,Ajax什麼同步非同步真的都是自學者的痛啊,像是一個新的領域一樣
土法煉鋼,想辦法跟著打,邊打邊學,多打幾次希望會渡過障礙。
這幾天都每天redo一次吧
重點:fetch(), regex, .innerHTML
補充: Regex,RegExp 正規表示式
//資料來源
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
//fetch()學習
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data))
function findMatches(wordToMatch, cities){
return cities.filter(place => {
const regex = new RegExp(wordToMatch, 'gi');
return place.city.match(regex) || place.state.match(regex);
});
}
//number format
function numberWithCommas(x){
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function displayMatches(){
//get data first, and then others
const matchArray = findMatches(this.value, cities);
//json to html
const html = matchArray.map(place => {
//style
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
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);