【问题标题】:Change div HTML content with attribute from button on click单击时从按钮更改具有属性的 div HTML 内容
【发布时间】:2022-11-04 21:26:01
【问题描述】:

我在按钮上有一些数据属性,当单击这些按钮时,我需要将它们作为内容发送到 div。到目前为止,我的一部分代码是这样的:

function getDiscount() {

  var buttons = document.querySelectorAll(".form-button");

  buttons.forEach(function(item, index) {
    item.addEventListener('click', function() {
      var discount = getDiscount(this);
    });
  });

  function getDiscount(clicked_element) {
    var val = clicked_element.getAttribute("data-discount");
    return val;
  }
};
<div><span class="discount-amount">55</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>

我只是没有看到单击时如何使用属性更改 html

希望有人可以提供帮助。 非常感谢

【问题讨论】:

  • 仅供参考,您的标记有缺陷。您正在关闭带有 strong 标签的 span 元素。

标签: javascript html custom-data-attribute


【解决方案1】:

您已经定义了两个名为getDiscount 的函数,最好让它们具有不同的名称

function init(){

    var buttons = document.querySelectorAll(".form-button");

        buttons.forEach(function (item, index) {
            item.addEventListener('click', function(){    
                var discount = getDiscount(this);
                let span = document.querySelector('.discount-amount')
                span.innerHTML = '<strong>' + discount+ '</strong>%'
                //span.innerHTML =discount.bold()+ '%' // we can use bold() instead
            });
        });

        function getDiscount(clicked_element) {
            var val = clicked_element.getAttribute("data-discount");  
            return val;
        }
};

init()
<div><span class="discount-amount"><strong>55</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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多