首页 > 解决方案 > 使用 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>

标签: javascripthtml

解决方案


btn是元素,而不是属性的值。

您需要将结果分配给getAttribute变量并在innerHTML.

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

推荐阅读