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

JavaScript多div内容修改失效求助:点击按钮仅第一个div生效

问题根源

你的代码存在两个核心问题:

  1. 遍历每个.discount__Topics容器时,用document.querySelectorAll(".form-button")选中了页面所有按钮,导致按钮被重复绑定点击事件,逻辑混乱。
  2. 点击按钮时,document.querySelector('.discount-amount')只会返回页面中第一个匹配的元素,所以无论点击哪个按钮,都只会修改第一个容器里的折扣数值。
修复后的代码

JavaScript

const discounters = document.querySelectorAll(".discount__Topics");

discounters.forEach(container => {
    // 仅选择当前容器内的按钮,避免全局范围选择
    const buttons = container.querySelectorAll(".form-button");
    // 提前获取当前容器对应的折扣显示元素
    const discountDisplay = container.querySelector('.discount-amount');

    buttons.forEach(button => {
        button.addEventListener('click', function() {
            const discount = this.getAttribute("data-discount");
            discountDisplay.innerHTML = `<strong>${discount}</strong>`;
        });
    });
});

HTML

<div class="discount__Topics">
<div><strong class="discount-amount">38</strong>%</div>

<div class="offers">
  <button class="form-button" data-discount="38">Offer 1</button>
  <button class="form-button" data-discount="50">Offer 2</button>
  <button class="form-button" data-discount="22">Offer 3</button>
  <button class="form-button" data-discount="88">Offer 4</button>
</div>
</div>

<div class="discount__Topics">
<div><strong class="discount-amount">12</strong>%</div>

<div class="offers">
  <button class="form-button" data-discount="12">Offer 1</button>
  <button class="form-button" data-discount="32">Offer 2</button>
  <button class="form-button" data-discount="44">Offer 3</button>
  <button class="form-button" data-discount="55">Offer 4</button>
</div>
</div>
核心修改说明
  • 限定元素选择范围:所有元素选择操作都基于当前遍历的container(即单个.discount__Topics容器),确保按钮只影响自身所属容器内的折扣数值。
  • 避免重复绑定事件:每个容器仅处理内部的按钮,不会给页面所有按钮重复添加点击事件。
  • 简化逻辑:去掉冗余的getDiscount函数,直接在点击事件中获取按钮的data-discount属性值,代码更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:45:22