如何在卡片搜索无结果时显示'Card not found'文本(HTML/CSS/JS)
解决卡片搜索无匹配结果提示逻辑错误的问题
问题场景
卡片搜索功能存在两处异常:
- 无匹配结果时没有任何提示信息
- 调整后出现新错误:仅剩一张匹配卡片时,也会显示"Card not found"提示
需求明确为仅当完全没有匹配卡片时,才显示"Card not found"文本。
错误原因
原代码逻辑存在漏洞:在遍历卡片的循环中,遇到不匹配的卡片就触发提示显示,导致只要存在不匹配卡片就会弹出提示,而非仅在无任何匹配结果时触发。
修正方案
通过统计匹配卡片的总数,仅当总数为0时才显示提示,修正后的JavaScript代码如下:
function myFunction() { var input, filter, cards, cardContainer, noContent, title, i, matchCount = 0; input = document.getElementById("myFilter"); noContent = document.getElementById("no-content"); filter = input.value.toUpperCase(); cardContainer = document.getElementById("myItems"); cards = cardContainer.getElementsByClassName("blog-card"); noContent.style.display = "none"; for (i = 0; i < cards.length; i++) { title = cards[i].querySelector(".card-title"); if (title.innerText.toUpperCase().indexOf(filter) > -1) { cards[i].style.display = "block"; matchCount++; } else { cards[i].style.display = "none"; } } if (matchCount === 0) { noContent.style.display = "flex"; noContent.querySelector("h1").textContent = "Card not found"; } }
额外优化
可以直接将HTML中.no-content容器内的<h1>文本固定为"Card not found",这样就能移除JS中noContent.querySelector("h1").textContent = "Card not found";这一行代码,进一步简化逻辑。
内容的提问来源于stack exchange,提问作者Nicolas Castro
相关产品推荐
相关产品推荐

