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

点击按钮利用data属性修改对应div内容的实现问题

多组折扣组件点击更新功能修复

需求:点击带有data-discount属性的按钮时,将属性值更新到同一discount__Topics容器内的discount-amount元素中。

原代码问题分析

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

  • 每次遍历discount__Topics时,都全局获取所有.form-button并重复绑定点击事件,导致按钮被绑定多次冗余事件。
  • 使用document.querySelector('.discount-amount')只会获取页面中第一个匹配的元素,所以无论点击哪组按钮,都只会更新第一个容器的折扣值。

修复后的代码

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>

JavaScript

// 获取所有折扣按钮
const buttons = document.querySelectorAll('.form-button');

buttons.forEach(button => {
  button.addEventListener('click', function() {
    // 从当前按钮获取折扣值
    const discount = this.getAttribute('data-discount');
    // 向上遍历找到所属的discount__Topics容器
    const container = this.closest('.discount__Topics');
    // 在容器内找到对应的discount-amount元素
    const amountElement = container.querySelector('.discount-amount');
    // 更新内容
    amountElement.textContent = discount;
  });
});

代码说明

  1. 事件绑定优化:直接一次性获取所有按钮并绑定一次点击事件,避免重复绑定。
  2. 容器定位:使用Element.closest()方法从点击的按钮向上查找最近的discount__Topics父容器,确保操作的是当前按钮所属的组。
  3. 目标元素查找:在找到的容器内使用querySelector()获取对应的discount-amount,保证只更新当前组的折扣值。
  4. 内容更新:使用textContent替代innerHTML,更安全且适合纯文本更新场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:51:51