在纯Javascript中,如何确定在节点列表中单击了哪个元素

在纯Javascript中,如何确定在节点列表中单击了哪个元素,javascript,ecmascript-6,Javascript,Ecmascript 6,我有很多类名为“button”的按钮。我正在寻找一种方法,用纯javascript确定我单击了哪个按钮。使用jQuery我会这样做 jQuery(".button").index(this); 我一直在想办法解决这个问题 document.querySelectorAll(".button").onclick = () => { console.log("You clicked button number" + ???); } 这不会响应任何按钮,而document.query

我有很多类名为“button”的按钮。我正在寻找一种方法,用纯javascript确定我单击了哪个按钮。使用jQuery我会这样做

jQuery(".button").index(this);
我一直在想办法解决这个问题

document.querySelectorAll(".button").onclick = () =>
{
    console.log("You clicked button number" + ???);
}
这不会响应任何按钮,而
document.querySelector(“.button”)
仅选择第一个按钮。

1)使用onclick-in JavaScript
您可以使用
.forEach()
迭代每个按钮。
然后,您可以从每个单击事件中获取信息

document.querySelectorAll("button").forEach((button, index) => {
  button.onclick = (event) => {
    console.log("You clicked button number " + index);
    console.log("You clicked button with class " + event.toElement.className);
    console.log("You clicked button with text " + event.toElement.innerText);
  }
})
2)在HTML中使用onclick 您可以在
中使用

<button class="button teste" onclick="whatButton(this)">1</button>
<button class="button teste" onclick="whatButton(this)">2</button>
<button class="button teste" onclick="whatButton(this)">3</button>
3)使用addEventListener
这类似于
.onclick
,但您可以直接使用
来定位按钮元素

document.querySelectorAll("button").forEach((button, index) => {
  button.addEventListener("click", function() {
    console.log("You clicked button number " + index);
    console.log("You clicked button with class " + this.className);
    console.log("You clicked button with text " + this.innerText);
  })
})

这是您确定单击哪个按钮的方式

const buttons=document.querySelectorAll('.button');
按钮。forEach(按钮=>{
按钮。addEventListener('单击',(事件)=>{
console.log('点击:#id-'+事件.target.id);
})
})
按钮1
按钮2

按钮3
您可以使用
querySelectorAll
循环所有元素,并将事件附加到每个元素

这样做的主要缺点是将添加多个事件。此外,如果以后添加元素,您也必须将事件添加到元素中

另一个选项是使用委托事件,基本上这是将事件附加到某个父元素并等待单击,您可以将其附加到主体。可以附加到主体,但出于性能原因,如果可以附加到某个父元素,效果会更好

例如

constyouclicked=document.querySelector('.youClicked');
document.querySelector(“.buttons”)
.addEventListener('单击',(e)=>{
//让我们只看看按钮
//而不是这个部门
如果(e.target.tagName===‘按钮’){
youClicked.innerText=e.target.innerText;
}
});

一个
两个
三
四
五
六
七

你点击=> ?
您可以使用
。为此,您需要删除arrow函数并使用常规的
function(){}
。您需要调用
addEventListner
方法将事件附加到元素
文档。queryselectoral(“.button”)
将返回节点列表。您需要循环浏览此节点列表,并将单击事件侦听器添加到节点列表中的每个按钮。循环将为您提供当前按钮的索引
document.querySelectorAll("button").forEach((button, index) => {
  button.addEventListener("click", function() {
    console.log("You clicked button number " + index);
    console.log("You clicked button with class " + this.className);
    console.log("You clicked button with text " + this.innerText);
  })
})