JavaScript实时搜索框报错:Cannot read properties of undefined (reading 'classList') 求排查解决
问题原因分析及修复方案
先帮你拆解一下报错的核心原因:你代码里用了productos.forEach来遍历商品,但**productos这个变量根本没定义**!而且你在异步加载JSON的时候,给data数组里的每个商品对象加了card属性,但这个data数组并没有被赋值给一个能在搜索事件里访问到的变量,导致后续遍历的时候找不到带card属性的商品对象,自然就会报错“无法读取undefined的classList”。
另外还有个隐藏的异步执行顺序问题:traigoJson是异步函数,你在它后面直接绑定搜索事件的时候,JSON可能还没加载完成,页面上的商品卡片也还没生成,不过这不是当前报错的直接原因,但也得一起处理。
具体修复步骤
1. 定义全局的商品数组
在代码最顶部先声明一个全局的productos变量,用来存储加载后的商品数据:
let productos = [];
2. 把JSON数据赋值给全局数组
修改traigoJson函数,把获取到的data赋值给productos,这样后续搜索逻辑就能访问到带card属性的商品对象:
const traigoJson = async()=> { const respuesta = await fetch ('../stock.json') const data = await respuesta.json() productos = data; // 将加载到的商品数据赋值给全局变量 let contenedor = document.getElementById("container") // 遍历productos数组,保持和后续逻辑的一致性 productos.forEach((producto, indice) => { let card = document.createElement("div") card.classList.add("col-xl-3", "col-lg-3", "col-md-6", "col-sm-6", "hide", `${producto.deporte}`, "products") card.innerHTML = `<div class="glasses_box"> <figure><img src="${producto.imagen}" alt="esta es una foto de ${producto.nombre}"/></figure> <h3><span class="blu">$</span>${producto.precio}</h3> <p class="product-name">${producto.nombre}</p> <button type="button" class="btn btn-outline-secondary boton-comprar" id="asd" onClick = "agregarAlCarrito (${indice})">COMPRAR</button> </div>` contenedor.appendChild(card) producto.card = card; // 给每个商品对象绑定对应的DOM元素 }) }
3. 确保搜索事件在商品加载完成后绑定
因为traigoJson是异步的,直接在后面绑定事件可能会遇到商品还没加载好的情况,所以我们把事件绑定放在traigoJson执行完成之后:
// 用async/await确保商品加载完成后再绑定事件 async function initApp() { await traigoJson(); // 等待商品数据加载和DOM生成完成 const searchInput = document.getElementById("search-input") searchInput.addEventListener("input", e => { const value = e.target.value.toLowerCase() productos.forEach(producto => { const isVisible = producto.nombre.toLowerCase().includes(value) || producto.deporte.toLowerCase().includes(value) producto.card.classList.toggle("hide", !isVisible) }) }) } // 初始化应用 initApp();
这样修改后,就能解决你遇到的报错问题了:搜索事件触发时,遍历的是已经绑定了card属性的productos数组,自然就能正确访问到classList来切换hide类了。
内容的提问来源于stack exchange,提问作者user19473497
相关产品推荐
相关产品推荐

