简体   繁体   中英

Why is the first click not firing?

The first click isn't firing and I can't work out why.

All subsequent clicks work fine. If I reload the page, same problem: first click: nothing happens.

I've tried accessing other html elements as test in the queryselector but it doesn't make a difference.

Here's the code (I'm trying to do this in vanilla JS):

const cities = [];
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) 
  });
}

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; 

   // this only works on the second click:
  const searchResult = document.querySelectorAll('li'); 
  searchResult.forEach(el => {
    el.addEventListener('click', function(){
      console.log('hi'); 

  })})


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

searchInput.addEventListener('change', displayMatches); // change only fires once user navigates away from input field!
searchInput.addEventListener('keyup', displayMatches);

}


EDITED: The issue comes from the search input having focus, so the click on the suggestion will blur the input and then for some reason ignore the click event on the list item (see related discussion here ). In your case using mousedown instead of click seems to fix the issue, see updated snippet below.

 const cities = []; // fetch(endpoint) // .then(blob => blob.json()) // .then(data =>cities.push(...data)); // mocking fetch here _fetch = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve([ {city: 'Los Angeles', state: 'CA', population: '4M'}, {city: 'New York City', state: 'NY', population: '8.4M'}, {city: 'Atlanta', state: 'GA', population: '0.5M'}, ]); }, 1000); }); }; _fetch() .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); }); } 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">${place.population}</span> </li> `; }).join(''); suggestions.innerHTML = html; // this only works on the second click: const searchResult = document.querySelectorAll('li'); searchResult.forEach(el => { el.addEventListener('mousedown', e => { console.log(`Say hi to ${e.currentTarget.innerText}`); }); }); } const searchInput = document.querySelector('.search'); const suggestions = document.querySelector('.suggestions'); // change only fires once user navigates away from input field! searchInput.addEventListener('change', displayMatches); searchInput.addEventListener('keyup', displayMatches); 
 <input type="text" class="search" /> <ul class="suggestions"> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM