Javascript 阅读html';使用vanilla js创建数据属性

Javascript 阅读html';使用vanilla js创建数据属性,javascript,html,Javascript,Html,为什么我不能获取数据价格属性的值 我想获取数据价格值,进行转换,并将其添加到html标记中 我知道如何在jquery中实现,但不知道如何在js中实现 JS代码: let btn = document.getElementById('btn'); let counter = document.getElementById('counter'); btn.addEventListener("click", function () { btn.getAttribute('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>

卡片标题

一些基于卡片标题的快速示例文本,构成了卡片内容的大部分

2499р
控制台:

<a href="#" id="btn" data-price="2499" class="btn btn-primary">В корзину</a>

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

您需要将
getAttribute
的结果分配给一个变量,并在
innerHTML
中使用该变量

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

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

您需要将
getAttribute
的结果分配给一个变量,并在
innerHTML
中使用该变量

btn.addEventListener("click", function () {
    var btnValue = btn.getAttribute('data-price');
    counter.innerHTML = btnValue;
    console.log(btnValue);
});
返回实际的
数据价格
属性值

let attribute = element.getAttribute(attributeName);
在哪里

  • attribute
    是一个字符串,包含
    attributeName
    的值
  • attributeName
    是要获取其值的属性的名称
您需要将
计数器.innerHTML
设置为该值,如下所示:

const price = btn.getAttribute('data-price');
counter.innerHTML = price;
console.log(price);
返回实际的
数据价格
属性值

let attribute = element.getAttribute(attributeName);
在哪里

  • attribute
    是一个字符串,包含
    attributeName
    的值
  • attributeName
    是要获取其值的属性的名称
您需要将
计数器.innerHTML
设置为该值,如下所示:

const price = btn.getAttribute('data-price');
counter.innerHTML = price;
console.log(price);
您还可以使用
dataset
属性,可以像这样访问
btn.dataset.price

示例

函数myFunction(btn){
console.log(btn.dataset.price)
}
My按钮
您还可以使用
dataset
属性,可以像这样访问
btn.dataset.price

示例

函数myFunction(btn){
console.log(btn.dataset.price)
}

My按钮
您似乎想在使用属性之前分配属性的值。类似于
constprice=btn.getAttribute('data-price')似乎您希望在使用属性之前分配属性的值。类似于
constprice=btn.getAttribute('data-price')