我有以下JS ......
function displayMatches() {
const matchArray = findMatches(this.value, motorcycles);
const html = matchArray.map(bike=> {
const regex = new RegExp(this.value, 'gi');
const bike_year = bike.year.toString().replace(regex, `<span class="hl">${this.value}</span>`);
const bike_model = bike.model.replace(regex, `<span class="hl">${this.value}</span>`);
return`
<li>
<span class="name">${bike_year}, ${bike_model}, ${bike.make}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
...我在控制台中收到错误Uncaught TypeError: Cannot set property 'innerHTML' of null
。我尝试添加添加window.onload = function displayMatches()
,然后添加错误displayMatches is not defined
。
我是否在正确的位置添加了onload?
答案 0 :(得分:0)
确实,当我console.log(suggestions)
时,它为null ...其中searchInput返回了相应的html。罪魁祸首早在我的html代码中。我本来有......
<form class="search-form">
<input type="text" class="search" placeholder="Search for Year, Make or Model">
</form>
...所以我给我和UL添加了一系列建议:
<form class="search-form">
<input type="text" class="search" placeholder="Search for Year, Make or Model">
<ul class="suggestions"></ul>
</form>
现在就像魅力一样。谢谢!