使用JavaScript获取data属性值的方法

问题

I have next html:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Is it possible to get the attributes that beginning with data-, and use it in the JavaScript code like code below? For now I get null as result.

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

You need to access the dataset property:

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"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

本文文字及图片出自 出处

阅读余下内容
 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


京ICP备12002735号