在 JavaScript 代码中获取数据属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33760520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:26:37  来源:igfitidea点击:

get data attributes in JavaScript code

javascripthtmlcustom-data-attribute

提问by H. Pauwelyn

I have next html:

我有下一个 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 JavaScriptcode like code below? For now I get nullas result.

是否可以获取以 , 开头的属性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"
    });
});

回答by Josh Crozier

You need to access the datasetproperty:

您需要访问该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"
  });
});

Result:

结果:

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

回答by MarkPlewis

Because the datasetproperty wasn't supported by Internet Explorer until version 11, you may want to use getAttribute()instead:

由于datasetInternet Explorer 直到版本 11 才支持该属性,因此您可能需要getAttribute()改用:

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

Dataset documentation

数据集文档

getAttribute documentation

获取属性文档

回答by meskobalazs

You can access it as

你可以访问它

element.dataset.points

etc. So in this case: this.dataset.points

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

回答by ii iml0sto1

You could also grab the attributes with the getAttribute()method which will return the value of a specific HTML attribute.

您还可以使用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}`
);
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

回答by Basheer AL-MOMANI

if you are targeting data attribute in Html element,

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

document.datasetwill not work

document.dataset不管用

you should use

你应该使用

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

or

或者

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

回答by Peter Krauss

Modern browsers accepts HTML and SVG DOMnode.dataset

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

Using pure Javascript's DOM-node datasetproperty.

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

It is an old Javascript standard for HTML elements(since Chorme 8 and Firefox 6) but new for SVG(since year 2017 with Chorme 55.x and Firefox 51)... It is not a problem for SVG because in nowadays (2019) the version's usage shareis dominated by modern browsers.

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

The values of dataset's key-values are pure strings, but a good practice is to adopt JSON string formatfor non-string datatypes, to parse it by JSON.parse().

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

Using the datasetproperty in any context

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

Code snippet to getand setkey-value datasetsat HTML and SVG contexts.

在 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 )
<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>

回答by den232

Circa 2019, using jquery, this can be accessed using $('#DOMId').data('typeId')where $('#DOMId')is the jquery selector for your span element.

大约在 2019 年,使用 jquery,可以使用您的 span 元素的 jquery 选择器$('#DOMId').data('typeId')在哪里访问$('#DOMId')

回答by Akash Agrawal

Try this instead of your code:

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

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