我有下一个html:
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
是否可以获取以开头的属性data-,并在下面的 JavaScript 代码中使用它?现在我得到null了结果。
data-
null
document.getElementById("the-span").addEventListener("click", function(){ var json = JSON.stringify({ id: parseInt(this.typeId), subject: this.datatype, points: parseInt(this.points), user: "H. Pauwelyn" }); });
您需要访问dataset属性:
dataset
document.getElementById("the-span").addEventListener("click", function() { var json = JSON.stringify({ id: parseInt(this.dataset.typeid), subject: this.dataset.type, points: parseInt(this.dataset.points), user: "Luïs" }); });
结果:
// json would equal: { "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }