使用Vanilla JS读取HTML数据属性

为什么无法获取data-price属性的值?

我想获取数据价格值,进行转化,并将其添加到html标记中 我知道如何在jquery中做到这一点,但在js中不行

JS代码:

let btn = document.getElementById('btn');
let counter = document.getElementById('counter');

btn.addEventListener("click", function () {
    btn.getAttribute('data-price');
    counter.innerHTML = btn;
    console.log(btn);
});

HTML代码:

<div class="card" style="width: 18rem;">
    <img src="img/img3.jpg" class="card-img-top" alt="...">
    <div class="card-body">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <div  id="price" class="card__price">2499р</div>
        <a href="#" id="btn" data-price="2499" class="btn btn-primary">В корзину</a>
    </div>
</div>

安慰:

<a href="#" id="btn" data-price="2499" class="btn btn-primary">В корзину</a>
评论
  • 伊筱沫
    伊筱沫 回复

    btn is the element, not the value of the attribute.

    You need to assign the result of getAttribute to a variable and use that in the innerHTML.

    btn.addEventListener("click", function () {
        var btnValue = btn.getAttribute('data-price');
        counter.innerHTML = btnValue;
        console.log(btnValue);
    });
    
  • ramet
    ramet 回复

    getAttribute() returns the actual data-price attribute value.

    let attribute = element.getAttribute(attributeName);
    

    哪里

    • attribute is a string containing the value of attributeName.
    • attributeName is the name of the attribute whose value you want to get.

    You need to the set counter.innerHTML to that value like:

    const price = btn.getAttribute('data-price');
    counter.innerHTML = price;
    console.log(price);
    
  • bby
    bby 回复

    一定有东西溜走了。 由于对象上没有此类功能,因此最好使用以下代码。

    let btn = document.getElementById('btn');
    
    let counter = document.getElementById('counter');
      btn.addEventListener("click", function () {
          let data = btn.getAttribute('data-price');
          counter.innerHTML = data;
      });
    

    Also i created an example for you in this link https://jsfiddle.net/4daxzcuo/2/