前端搜索结果长度重复显示及图片路径渲染问题求助
Hey there! Let's tackle your two issues one by one:
问题1:搜索结果数量在每个结果项重复显示
The problem here is that you're placing the result count <span>${itemsMatch.length}</span> inside the map() loop—so it gets rendered once for every matching item. To fix this, move that count element outside the loop so it only appears once at the top of your results.
Here's the corrected code:
const resultHtml = (itemsMatch) => { if (itemsMatch.length > 0) { // Render the count just once, outside the item loop const html = `<span>${itemsMatch.length}</span>` + itemsMatch .map( (item) => ` <div class="card"> <div class="items-img"> </div> <div class="items-info"> <h4>${item.title}</h4> <small>${item.path}</small> </div> </div> ` ) .join(''); itemList.innerHTML = html; } };
问题2:页面显示图片路径而非实际图片
Right now you're inserting the image path string directly into the HTML, which is why it shows up as plain text instead of an image. You need to wrap that path in an <img> tag, using the path as the src attribute (adding an alt text for accessibility is also a great practice).
Here's the fixed code for this issue:
const resultHtml = (itemsMatch) => { if (itemsMatch.length > 0) { const html = `<span class="items-results">${itemsMatch.length} Resultados</span>` + itemsMatch .map( (item) => ` <div class="card"> <div class="items-img"> <!-- Wrap the image path in an img tag to render it as an image --> <img src="${item.image}" alt="${item.title}" /> </div> <div class="items-info"> <h4>${item.title}</h4> <small>${item.path}</small> </div> </div> ` ) .join(''); console.log(html); itemList.innerHTML = html; } };
内容的提问来源于stack exchange,提问作者VascoM

