簡體   English   中英

有人可以解釋此代碼示例中this.value的含義嗎?

[英]Can someone explain what this.value means in this example of code?

我剛接觸JavaScript並且仍在學習中,我最近編寫了這段代碼並且可以正常工作,但是我不明白th​​is.value在這種情況下指的是什么:

function displayMatches() {
 const matchArray = findMatches(this.value, cities); //what does this.value refer to?

 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">${place.city}, ${stateName}</span>
  <span class="population">${numberWithCommas(place.population)}</span>
</li>
`;
}).join ('');
suggestions.innerHtml = html;
}

我認為這是在wordsToMatch中引用的,這是所有代碼:

const cities = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));

function findMatches(wordToMatch) {
  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;
}

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

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);

任何人都可以幫我解釋一下,以便我理解嗎? 非常感謝! 我發現整個.this()方法仍然很混亂。

當您調用綁定某個事件的某個方法時, 就是該事件發送給處理程序方法的信息。 在這段代碼中:

searchInput.addEventListener('change', displayMatches);

您正在監聽元素searchInput,然后在displayMatches()上下文中, 是searchInput元素。

這樣,this.value是searchInput.value。

你明白了嗎?

在函數內部,此值取決於函數的調用方式。 它是指調用該函數的DOM元素。
假設這是您的JavaScript:

function alertMessage () {
    alert(this.value);
}

這是您的HTML:

<input type="text" onmousehover="alertMessage()" value="Test">

當鼠標懸停在輸入元素上時,JavaScript將警告“ Test”,因為調用該函數的輸入值為Test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM