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

调整商品数量后AddToCart函数的qt参数未更新该如何修复?

问题修复方案

根因分析

你在拼接商品DOM字符串时,直接将初始数量qt=1硬编码到了AddToCart的调用参数中,按钮渲染完成后onclick属性就固定为AddToCart(1, 商品ID)。后续点击增减按钮仅修改了.qt标签的显示文本,没有同步更新按钮上绑定的固定参数,因此AddToCart拿到的永远是初始值1。

修复步骤

1. 调整加购按钮的参数传递

修改newItem中加购按钮的onClick绑定逻辑,不再传递固定的初始qt值,改为传递当前商品的索引i和商品IDitemId:

// 把原来的按钮代码
<button class="btn-add-to-cart" onClick='AddToCart(${qt}, ${itemId})'>Add to cart</button>
// 替换为
<button class="btn-add-to-cart" onClick='AddToCart(${i}, ${itemId})'>Add to cart</button>

2. 修改AddToCart函数实时取最新数量

调整AddToCart的实现,进入函数后先根据商品索引获取对应节点的当前数量值:

function AddToCart(i, itemId) {
    // 实时读取当前商品的最新数量
    const currentItem = document.getElementById(`item_${i}`);
    const currentQt = parseInt(currentItem.querySelector('.qt').textContent) || 1;

    var url = "https://localhost:44335/Cart/Order";
    var data = {
        Quantity: currentQt,
        ItemId: itemId
    }
    axios.post(url, data)
        .then(function (response) {
            // 后续业务逻辑
        })
        .catch(function (error) {
            console.log(error)
        })
}

修改完成后每次点击加购按钮都会读取最新的数量值,不会再出现参数不更新的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:06:01