您可以在下面看到我的ES6代码进行API调用,然后用返回的数据填充容器(1个数据= 1个.searchResult
子元素)。我想在每个调用类mousedown
中的回调方法的事件监听器上添加一个p_selectResult
事件监听器。
问题是,当我在回调箭头函数中console.log(this.p_selectResult)
(在for
循环内)时,我不确定。
class WeatherApp {
/*******......*********/
/**
* Auto completion
*/
p_handleAutoCompletion() {
let searchValue = document.querySelector('#searchInput').value;
if (searchValue !== '') {
let xhttp = new XMLHttpRequest();
xhttp.addEventListener('readystatechange', () => {
if (xhttp.readyState === 4 && xhttp.status === 200) {
// some code...
let results = document.querySelectorAll('.searchResult');
for (let i = 0; i < results.length; i += 1) {
console.log(this.p_selectResult); //this.p_selectResult undefined
results[i].addEventListener('mousedown', this.p_selectResult);
}
}
});
let requestAddr = '...';
xhttp.open('GET', requestAddr, true);
xhttp.send();
}
else {
/*...*/
}
}
p_selectResult() {
console.log('yes');
}
/***.......*****/
}