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

为什么.textContent无法获取JavaScript动态生成HTML的元素文本内容

核心问题原因

  • 元素查询时机错误:你执行let amountItems = document.querySelector('.amount-items')的时候,你要找的amount-items类元素还根本不存在——此时你还没给newItem赋值innerHTML,也没有把新元素挂载到DOM上,querySelector找不到匹配元素就会返回null,调用null.textContent自然拿不到值。
  • 查询范围错误:你要获取的是你刚创建的newItem内部的amount-items元素,用全局的document.querySelector只会匹配页面中已存在的第一个对应类元素,就算后续元素创建完成,也拿不到你当前新增节点里的元素。
  • 其他逻辑漏洞:你写的Number(amountItems.innerHTML) + 1没有赋值操作,计算完的结果直接丢弃了,计数不会生效;循环里重复定义了变量i,会和外层的i产生变量冲突。

修正方案

你需要先给newItem设置完innerHTML,再从newItem节点下查询对应的元素,调整代码顺序即可:

// 购物车下拉容器
const cartDropdown = document.querySelector('.cart-dropDown-items');
// 所有加入购物车按钮
const addToCartButtons = document.querySelectorAll('.addToCart');
// 商品价格节点
const foodPrices = document.querySelectorAll('.selection-row-title');
// 商品名称节点
const foodNames = document.querySelectorAll('.selection-row-foodName');
// 商品重量节点
const foodWeights = document.querySelectorAll('.selection-row-weight');

// 用Map存储商品,键为商品id,值为商品信息,方便快速查询更新
const items = new Map();
let total = 0;

for (let i=0; i<addToCartButtons.length; i++) {
    addToCartButtons[i].addEventListener('click', function() {
        const currentItemId = addToCartButtons[i].value;
        const currentItemPrice = Number(foodPrices[i].innerHTML.substring(1));
        const currentItemName = foodNames[i].innerHTML;
        
        // 商品已在购物车,直接更新数量
        if (items.has(currentItemId)) {
            const existItem = items.get(currentItemId);
            existItem.amount += 1;
            existItem.amountEl.textContent = existItem.amount;
            existItem.priceEl.textContent = existItem.amount * currentItemPrice;
            return;
        }
        
        // 商品不在购物车,新增节点
        const newItem = document.createElement('div');
        newItem.className = 'dropDown-item';
        // 先给newItem赋值innerHTML
        newItem.innerHTML =                 
            `<div class='dropDown-title dropDown-info'>
                ${currentItemName}
            </div>
            <div class='dropDown-amount dropDown-info'>
                <p class='amount-items'>1</p>
            </div>
            <div class='dropDown-price dropDown-info'>
                ${currentItemPrice}
            </div>`;
        // 再从newItem内部查询对应的元素
        const amountItems = newItem.querySelector('.amount-items');
        const priceEl = newItem.querySelector('.dropDown-price');
        // 把商品信息存入Map
        items.set(currentItemId, {
            amount: 1,
            amountEl: amountItems,
            priceEl: priceEl
        });
        // 挂载到DOM
        cartDropdown.appendChild(newItem);
    })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:45:00