如果我执行以下操作:
$('.js-element').attr("data-count", 2)
然后我可以使用 CSS 显示该值:
.js-element:after {
content: attr(data-count);
}
但如果我执行以下操作:
$('.js-element').data("count", 2)
然后相同的 CSS 代码什么都不显示。
据我了解,不同之处在于,在第一种情况下,我只是在 HTML 元素上设置一个属性,我恰好以数据为前缀,而在第二种情况下,我正在设置 HTML 元素的数据集属性。
我的问题是:
- 可以认为其中一种方法优于另一种方法吗?
- 如何让 CSS 显示数据集中的值?
最佳答案
As I understanding the difference is that in the first case I am just setting an attribute on the HTML element that I happen to prefix with data
是
while in the second case I am setting the dataset property of HTML element.
没有。您正在设置 jQuery 的内部数据存储。
Can one of the methods be considered better than the other?
这是主观的
How can I get CSS to show values from the dataset?
设置数据集值 (document.querySelector('.js-element').dataset.count = 2
),它会自动映射到属性上。
关于javascript - 在 CSS 中显示来自数据集的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50834471/