You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:10:28