如何在 JavaScript 代码中获取数据属性的值?

How can I get the values of data attributes in JavaScript code?

我有下一个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"
    });
});

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

您可以访问它

element.dataset.points

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

因为 Internet Explorer 直到版本 11 才支持 dataset 属性,您可能想改用 getAttribute()

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

Dataset documentation

getAttribute documentation

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

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

如果您的目标是 Html 元素中的数据属性,

document.dataset 不行

你应该使用

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

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

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

使用 pure Javascript's DOM-node dataset property.

它是一个 old Javascript standard for HTML elements (since Chorme 8 and Firefox 6) but new for SVG(自 2017 年起使用 Chorme 55.x 和 Firefox 51)...这对 SVG 来说不是问题,因为现在(2019 年)版本的 使用份额 由现代浏览器主导。

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

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

getset key-value datasets at 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>

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

您还可以使用 getAttribute() 方法获取属性,该方法将 return 特定 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>

您实际上可以使用 JQuery 以非常简单的方式完成此操作

$(document).on('click', '.the-span', function(){

let type = $(this).data("type");

});
document.getElementById('selectTbl').addEventListener('change', function () {
    $("#selectTbl").val();
    var style = $(this).val() == 1 ? 'block' : 'none';
    document.getElementById('TblAdmin').style.display = style;

    var style = $(this).val() == 2 ? 'block' : 'none';
    document.getElementById('TblMech').style.display = style;

    var style = $(this).val() == 3 ? 'block' : 'none';
    document.getElementById('TblUser').style.display = style;

    var style = $(this).val() == 4 ? 'block' : 'none';
    document.getElementById('TblBiz').style.display = style;
});

抱歉打扰了,我想你已经得到了答案。有人可以帮我吗? 这里我想显示 div 即 TblAdminTblMechTblUserTblBiz。我目前正在使用 NiceSelect 但在 select 下拉列表中它具有数据值属性。它实际上不是 select 而是 list-item 在 unordered-list.

里面

像这里显示的图片, https://drive.google.com/file/d/1VyHDMb1Gl4PYBe19XZt1Z8Z-2OLAS1mx/view?usp=sharing