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

当前回答

您还可以使用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" }

你可以访问它

element.dataset.points

等。这里是this。dataset。points

实际上,您可以使用JQuery以一种非常简单的方式来实现这一点

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

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

});

您还可以使用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> .

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是TblAdmin, TblMech, TblUser, TblBiz。我目前使用的是NiceSelect,但在选择下拉列表中有数据值属性。它实际上不是select而是无序列表中的list-item。

就像这张图, https://drive.google.com/file/d/1VyHDMb1Gl4PYBe19XZt1Z8Z-2OLAS1mx/view?usp=sharing