在JavaScript代码中获取数据属性

H. *_*lyn 107 html javascript custom-data-attribute

我有下一个HTML:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
Run Code Online (Sandbox Code Playgroud)

是否有可能获得开头的属性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"
    });
});
Run Code Online (Sandbox Code Playgroud)

Jos*_*ier 134

您需要访问该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"
  });
});
Run Code Online (Sandbox Code Playgroud)

结果:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
Run Code Online (Sandbox Code Playgroud)

  • 请记住,根据 MDN,数据集标准不适用于 Internet Explorer &lt; 11。https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#Issues“支持 IE 10并且在您需要使用 getAttribute() 访问数据属性的情况下。” (5认同)
  • 知道这如何与打字稿一起使用吗?因为在打字稿中这会产生错误,**对象可能未定义** (2认同)

Mar*_*wis 86

因为dataset版本11之前Internet Explorer不支持该属性,所以您可能希望使用getAttribute():

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

数据集文档

getAttribute文档


ii *_*to1 20

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

var elem = document.getElementById('the-span');

var typeId = elem.getAttribute('data-typeId');
var type   = elem.getAttribute('data-type');
var points = elem.getAttribute('data-points');
var important = elem.getAttribute('data-important');

console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`
);
Run Code Online (Sandbox Code Playgroud)
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
Run Code Online (Sandbox Code Playgroud)


mes*_*azs 18

你可以访问它

element.dataset.points
Run Code Online (Sandbox Code Playgroud)

等.在这种情况下: this.dataset.points


Bas*_*ANI 8

如果您在 Html 元素中定位数据属性,

document.dataset 不管用

你应该使用

document.querySelector("html").dataset.pbUserId
Run Code Online (Sandbox Code Playgroud)

或者

document.getElementsByTagName("html")[0].dataset.pbUserId
Run Code Online (Sandbox Code Playgroud)


Pet*_*uss 6

现代浏览器接受 HTML 和 SVG DOMnode.dataset

使用 纯 Javascript 的 DOM 节点数据集属性

它是HTML 元素的旧 Javascript 标准(自 Chorme 8 和 Firefox 6 起),但对于 SVG 来说是新标准(自 2017 年 Chorme 55.x 和 Firefox 51 起)...这对于 SVG 来说不是问题,因为在当今(2019 年)该版本的使用份额由现代浏览器主导。

数据集的键值是纯字符串,但一个好的做法是对于非字符串数据类型采用 JSON 字符串格式,通过JSON.parse().

在任何上下文中使用数据集属性

用于在 HTML 和 SVG 上下文中获取设置键值数据集的代码片段。

console.log("-- GET values --")
var x = document.getElementById('html_example').dataset;
console.log("s:", x.s );
for (var i of JSON.parse(x.list)) console.log("list_i:",i)

var y = document.getElementById('g1').dataset;
console.log("s:", y.s );
for (var i of JSON.parse(y.list)) console.log("list_i:",i)

console.log("-- SET values --");
y.s="BYE!"; y.list="null";
console.log( document.getElementById('svg_example').innerHTML )
Run Code Online (Sandbox Code Playgroud)
<p id="html_example" data-list="[1,2,3]" data-s="Hello123">Hello!</p>
<svg id="svg_example">
  <g id="g1" data-list="[4,5,6]" data-s="Hello456 SVG"></g>
</svg>
Run Code Online (Sandbox Code Playgroud)