如何在JavaScript代码中获取数据属性的值? [英] How can I get the values of data attributes in JavaScript code?

查看:66
本文介绍了如何在JavaScript代码中获取数据属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个html:

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

是否可以获取以data-开头的属性,并在 JavaScript 代码中使用它,例如下面的代码?现在,我得到null作为结果.

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

推荐答案

您需要访问

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

结果:

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

这篇关于如何在JavaScript代码中获取数据属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆