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

电商网站搜索栏显示正常但无法筛选商品问题求助

电商搜索栏功能修复方案

问题根源

  1. 类选择器错误:document.querySelectorAll("pro")缺少类选择器前缀.,无法定位到class为pro的商品容器,导致后续筛选逻辑没有作用对象。
  2. 循环逻辑关联混乱:依赖pname.length(所有h5标签的数量)进行循环,但product与pname的集合对应关系不可靠,容易出现索引不匹配的情况。

修正后的代码

JavaScript 代码

const search = () => {
    const searchbox = document.getElementById("search-item").value.toUpperCase();
    // 正确选中所有class为pro的商品元素
    const products = document.querySelectorAll(".pro");

    // 遍历每个商品元素
    products.forEach(product => {
        // 获取当前商品内的h5标签
        const match = product.querySelector('h5');
        if (match) {
            const textvalue = match.textContent.toUpperCase();
            // 根据匹配结果控制商品显示/隐藏
            product.style.display = textvalue.includes(searchbox) ? "" : "none";
        }
    });
}

HTML 代码(无需修改)

<form>
    <i class="fas fa-search"></i>
    <input type="text" name="" id="search-item" placeholder="Search here" onkeyup="search()">
</form>

<section id="product1" class="section-p1">
    <div class="pro-container" id="game-list">
        <div class="pro" onclick="window.location.href='sproduct.html'">
            <img src="img/products/f1.jpg" alt="">
            <div class="des">
                <span>Developer : CD PROJEKT RED</span>
                <h5>CYBERPUNK</h5>
                <div class="star">
                    <i class="fa-solid fa-star"></i>
                    <i class="fa-solid fa-star"></i>
                    <i class="fa-solid fa-star"></i>
                    <i class="fa-solid fa-star"></i>
                    <i class="fa-regular fa-star"></i>
                </div>
                <h4>$85</h4>
            </div>
            <a href="#"><i class="fa-regular fa-bookmark bookmark"></i></a>
        </div>
        <!-- 更多商品元素 -->
    </div>
</section>

关键修正说明

  • 补上类选择器前缀.,确保能正确获取所有商品容器。
  • 使用forEach遍历商品集合,逻辑更清晰,避免索引不匹配问题。
  • 用includes()替代indexOf(),代码更简洁易读。

内容的提问来源于stack exchange,提问作者Creasic Dang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:25:16