为什么第一次点击没有触发?

时间:2019-07-27 16:08:48

标签: javascript

第一次点击没有触发,我无法弄清楚原因。

所有后续点击都可以正常运行。如果我重新加载页面,则存在相同的问题:第一次单击:什么也没发生。

我已经尝试在queryselector中作为测试访问其他html元素,但这没有什么不同。

这是代码(我正在香草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);

}


1 个答案:

答案 0 :(得分:0)

已编辑:问题来自具有焦点的搜索输入,因此对建议的单击将blur输入,然后由于某种原因而忽略列表项上的click事件(请参阅相关讨论{{3} }。就您而言,使用mousedown而非click似乎可以解决此问题,请参见下面的更新代码段。

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>