我有下一个html:

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

是否有可能获得以data开始的属性,并在JavaScript代码中使用它,如下面的代码?现在我得到的结果是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"
    });
});

当前回答

因为Internet Explorer直到版本11才支持dataset属性,所以你可能想使用getAttribute()来代替:

document.getElementById("the-span").addEventListener("click", function(){
  console.log(this.getAttribute('data-type'));
});

数据集的文档

getAttribute文档

其他回答

你可以访问它

element.dataset.points

等。这里是this。dataset。points

您还可以使用getAttribute()方法获取属性,该方法将返回特定HTML属性的值。

var elem = document.getElementById('the-span'); var typeId = elem.getAttribute('data-typeId'); var type = elem.getAttribute('data-type'); var points = element . getattribute ('data-points'); var important = element . getattribute ('data-important'); console.log(' typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important} ' ); <span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span> .

你需要访问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" }

试试这个,而不是你的代码:

var type=$("#the-span").attr("data-type");
alert(type);

如果你的目标数据属性在Html元素,

文档。数据集将无法工作

你应该使用

document.querySelector("html").dataset.pbUserId

or

document.getElementsByTagName("html")[0].dataset.pbUserId