【问题标题】:How can I get the values of data attributes in JavaScript code?如何获取 JavaScript 代码中数据属性的值?
【发布时间】:2016-02-19 00:51:00
【问题描述】:

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

【问题讨论】:

  • 现在(2019 年)还可以将节点的数据集属性与 SVG 节点(!)一起使用,请参阅 answer below 或使用 with D3

标签: javascript html custom-data-attribute


【解决方案1】:

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

【讨论】:

  • 请记住,根据 MDN,数据集标准不适用于 Internet Explorer developer.mozilla.org/en-US/docs/Learn/HTML/Howto/…“要支持 IE 10 及以下版本,您需要使用 getAttribute() 访问数据属性。 "
  • 知道这将如何与打字稿一起使用吗?因为在打字稿中这给出了一个错误,object可能是未定义的
【解决方案2】:

由于 Internet Explorer 直到版本 11 才支持 dataset 属性,您可能希望改用 getAttribute()

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

Dataset documentation

getAttribute documentation

【讨论】:

    【解决方案3】:

    你可以访问它

    element.dataset.points
    

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

        document.dataset 不起作用

        你应该使用

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

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

        【讨论】:

          【解决方案6】:

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

          使用pure Javascript's DOM-node dataset property

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

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

          在任何上下文中使用 dataset 属性

          代码 sn-p 到 HTML 和 SVG 上下文中的 getset 键值数据集

          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>

          【讨论】:

            【解决方案7】:

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

            【讨论】:

              【解决方案8】:

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

              $(document).on('click', '.the-span', function(){
              
              let type = $(this).data("type");
              
              });
              

              【讨论】:

              • 随着 Vue、React 和 Angular 等框架的爆炸式增长,使用 jQuery 与大多数这些框架的做法背道而驰。如果 OP 使用其中之一,那么他们应该积极避免使用 jQuery。此外,他们在 JavaScript 而不是 jQuery 中要求它,这就是为什么我投了反对票。
              【解决方案9】:

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

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

              【讨论】:

              • Asker 没有提到 jQuery,这甚至不是一个好的 jQuery。应该改为.data('type');
              • 最重要的是,使用这个“而不是你的代码”的建议太宽泛了;提问者希望保持事件处理设置和JSON 结果,而不是data-type 属性的alert
              • 这是 jquery,不是纯 javascript。
              猜你喜欢
              • 2021-08-29
              • 2011-12-15
              • 2023-01-29
              • 1970-01-01
              • 2016-11-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-01-28
              相关资源
              最近更新 更多