单击元素时如何获取元素的数据 ID?

How to have the data-id of an element when you click on it?

我创建了几个按钮,并在循环中给它们一个 ID,我希望当我们点击它时,它的 ID 会显示在控制台中。 这是我尝试做的,但程序 returns 循环后分配的最后一个 ID。

for (var i = 0; i < 3; i++) {
var button = document.createElement('button');
button.textContent = "Add to cart"; 
button.setAttribute("data-id", i+1);
card.appendChild(button);
button.onclick = function() {
  let attribut = button.getAttribute("data-id");
  console.log(attribut)
};

}

当调用 onclick 时,button 仍设置为循环中的最后一个按钮;您的 onclick 中没有提及 button。相反,尝试将事件 (e) 传递到 onclick,然后使用 e.target.

引用事件的目标

for (var i = 0; i < 3; i++) {
  var button = document.createElement('button');
  button.textContent = "Add to cart"; 
  button.setAttribute("data-id", i+1);
  document.body.appendChild(button);
  button.onclick = function(e) {
    let attribut = e.target.getAttribute("data-id");
    console.log(attribut)
  };
}