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

Firebase自动生成ID致购物车添加商品报错的解决咨询

问题:Firebase自动生成ID引发购物车功能报错

错误信息:未捕获引用错误:HTMLButtonElement.onclick处Nh63f2zxDC9C_6m25Fc未定义

使用Firebase push自动生成商品ID后,点击「Add To Card」按钮触发上述错误;将ID改为数字1时功能正常,但希望保留自动生成ID的方案解决问题。


解决方案

核心问题:Firebase生成的字符串ID直接作为参数写入内联onclick时,JS会将其解析为变量名而非字符串,不存在对应变量所以报错。以下两种方案均可修复:

方案一:用事件监听器替代内联onclick(推荐)

这种写法更符合现代JS规范,避免字符串解析问题:

function initApp(){
    firebase.database().ref('Products/').once('value').then(function(snapshot){
        var data=snapshot.val();
        products = data;

        for(let[key,value] of Object.entries(products)){
            let newDiv = document.createElement('div');
            newDiv.classList.add('item');
            // 先创建元素结构,不包含内联onclick
            newDiv.innerHTML = `
                <img src="${value.image}">
                <div class="title">${value.pname}</div>
                <div class="price">${value.price.toLocaleString()}</div>
                <button>Add To Card</button>`;
            // 获取按钮并绑定点击事件
            const addBtn = newDiv.querySelector('button');
            addBtn.addEventListener('click', () => addToCard(key));
            list.appendChild(newDiv);
        }
    });
}

方案二:将ID作为字符串传入内联onclick

如果坚持用内联写法,需给ID添加引号,让JS识别为字符串参数:

// 修改按钮的innerHTML部分
<button onclick="addToCard('${key}')">Add To Card</button>

额外修复:购物车加减按钮的同类问题

reloadCard函数中生成的加减按钮也存在相同问题,需同步处理:

事件监听器版本(推荐)

function reloadCard(){
    listCard.innerHTML = '';
    let count = 0;
    let totalPrice = 0;
    // 改用Object.entries遍历对象(listCards是字符串键的对象,不是数组)
    Object.entries(listCards).forEach(([key, value]) => {
        totalPrice = totalPrice + value.price;
        count = count + value.quantity;
        if(value != null){
            let newDiv = document.createElement('li');
            newDiv.innerHTML = `
                <div><img src="${value.image}"/></div>
                <div>${value.pname}</div>
                <div>${value.price.toLocaleString()}</div>
                <div>
                    <button class="decrease">-</button>
                    <div class="count">${value.quantity}</div>
                    <button class="increase">+</button>
                </div>`;
            // 绑定加减按钮事件
            const decreaseBtn = newDiv.querySelector('.decrease');
            const increaseBtn = newDiv.querySelector('.increase');
            decreaseBtn.addEventListener('click', () => changeQuantity(key, value.quantity - 1));
            increaseBtn.addEventListener('click', () => changeQuantity(key, value.quantity + 1));
            listCard.appendChild(newDiv);
        }
    })
    total.innerText = totalPrice.toLocaleString();
    quantity.innerText = count;
}

内联写法版本

给ID参数添加引号:

<button onclick="changeQuantity('${key}', ${value.quantity - 1})">-</button>
<button onclick="changeQuantity('${key}', ${value.quantity + 1})">+</button>

内容的提问来源于stack exchange,提问作者Argus Gale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:44:54