首页 > 解决方案 > 返回 data-football 属性名

问题描述

如果我有以下代码:

<button id="btnOne" data-football="Mitre">Press Me</button>

我将如何获得数据标签的名称,所以在这种情况下它将是“数据足球”。我知道如何获得值,但想知道如何获得数据标签的名称——在这种情况下,按下按钮时的数据足球。

IE,

$(document).on("click", "button", function(){
   // Get the name of the attribute (data-football - not the value);
});

谢谢。

标签: javascriptjquery

解决方案


您可以使用attributes属性来获取 HTML 标记的所有属性

<div id="_id" data-football='test'></div>
  <script>
        const attrs = document.getElementById('_id').attributes
        const keyName = attrs[1].nodeName // will be data-football
  </script>

推荐阅读