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

修复JS动态创建商品卡片:仅库存为no的卡片变灰的问题

修复商品卡片库存状态显示错误

原代码存在的问题

  • 拼写错误:模板字符串中使用了错误的变量名stoak,正确应为stock;类实例变量名CardStoak存在拼写错误,建议改为CardStock以统一拼写。
  • 条件判断不匹配:代码中判断库存的条件是stock === 'нет'(俄语“无”),但商品数组中库存状态值为'no',两者不匹配,导致判断逻辑失效。
  • 卡片与商品对应逻辑错误:通过内层循环遍历所有商品来判断库存,会导致只要存在一个库存为no的商品,所有卡片都会被添加灰色样式——因为每个卡片都会被遍历到该商品的条件判断。

修复后的代码

const goods = [
    {
        img: "/img/iphone.jpg",
        name: 'iphone',
        model: 'Gky-42-s',
        stock: 'yes'
    },
    {
        name: 'Samsung',
        model: 'JIj-21s',
        stock: 'yes'
    },
    {
        name: 'Honor',
        model: 'Jiu-21-e-2',
        stock: 'no'
    },
]

let wrapper = document.querySelector('#wrapper');
class Card {
    render() {
        let htmlCard = '';
        // 渲染时直接判断库存,添加对应的类
        goods.forEach(({name, model, stock, img}) => {
            // 根据stock值决定是否添加gray类
            const cardClass = stock === 'no' ? 'card gray' : 'card';
            htmlCard += `
            <div class="${cardClass}">
                <img src="${img || ''}"> <!-- 处理没有img的商品,避免显示无效路径 -->
                <span>${name}</span>
                <span>${model}</span>
                <span>${stock}</span>
            </div>`
        });
        wrapper.innerHTML = htmlCard;
    }
}

let CardStock = new Card();
CardStock.render();

额外优化说明

  • 在渲染卡片时直接根据stock值添加gray类,避免后续再次遍历DOM元素,提升代码效率。
  • 处理了商品没有img字段的情况,给src设置空字符串,避免浏览器加载无效图片路径。

内容的提问来源于stack exchange,提问作者the Alex Fire

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:35:17