JavaScript搜索栏建议元素无法正常显示问题求助
问题解决:搜索建议直接显示
${resultItem.name}而非实际内容 你的问题出在字符串插值的语法错误上:JavaScript的模板字符串(用来解析${变量}的语法)必须用**反引号()**包裹,而你当前用的是单引号('),导致${resultItem.name}`被当成纯文本输出,没有解析成变量值。
修正后的JavaScript代码
const articles = [{ name: 'toto' }, { name: 'mamam' }, { name: 'tampon' }, { name: 'TANTON' }]; const rechercheInput = document.getElementById('rechercheInput'); rechercheInput.addEventListener('keyup', function() { const input = rechercheInput.value; const result = articles.filter(item => item.name.toLocaleLowerCase().includes(input.toLocaleLowerCase())); let suggestion = ''; result.forEach(resultItem => { // 把单引号换成反引号,让模板字符串生效 suggestion += `<div class="suggestion">${resultItem.name}</div>`; }); document.getElementById('suggestions').innerHTML = suggestion; })
更简洁的写法(推荐)
用map生成所有建议元素的字符串数组,再用join('')拼接,比forEach累加更高效易读:
const articles = [{ name: 'toto' }, { name: 'mamam' }, { name: 'tampon' }, { name: 'TANTON' }]; const rechercheInput = document.getElementById('rechercheInput'); rechercheInput.addEventListener('keyup', function() { const input = rechercheInput.value; const result = articles.filter(item => item.name.toLocaleLowerCase().includes(input.toLocaleLowerCase())); // map+join写法更简洁 const suggestion = result.map(resultItem => `<div class="suggestion">${resultItem.name}</div>` ).join(''); document.getElementById('suggestions').innerHTML = suggestion; })
关键修改点
- 将包裹插值字符串的单引号(')替换为反引号(
),让JavaScript识别并解析${resultItem.name}`为变量值 - 可选:用
map替代forEach,代码逻辑更清晰,性能更优
内容的提问来源于stack exchange,提问作者Pathia Nanto
相关产品推荐
相关产品推荐

