javascript - 使用 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
是元素,而不是属性的值。
您需要将结果分配给getAttribute
变量并在innerHTML
.
btn.addEventListener("click", function () {
var btnValue = btn.getAttribute('data-price');
counter.innerHTML = btnValue;
console.log(btnValue);
});
推荐阅读
- reactjs - React:如何将值传递给我的主 App() 函数
- javascript - 如何从数据库中添加日期的月份并在网页中显示
- c++ - 哪个是在 C++ 中存储 1 个键和 2 个值的最佳数据结构
- python - 如何检查函数是否在python中返回一种类型的数据或另一种类型的数据
- ios - iOS上的德语蓝牙键盘字符错误
- spring - ibm rad 8, was 7, spring 3.2.9 和 xerces 问题
- elasticsearch - Elasticsearch 基本搜索的非法状态异常
- rust - HashMap 编辑值和 Iter Rust
- javascript - 样式未从源 Excel 文件中复制
- django - 如何在 Django 中显示自定义错误页面