繁体   English   中英

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

[英]In plain Javascript how do I determine which element I clicked in a Nodelist

我有许多类名为“button”的按钮。 我正在寻找一种方法来确定我点击了哪个按钮。 使用 jQuery 我会做

jQuery(".button").index(this);

我一直试图找到一种方法

document.querySelectorAll(".button").onclick = () =>
{
    console.log("You clicked button number" + ???);
}

这不会响应任何按钮,而document.querySelector(".button")只选择第一个按钮。

1) 在 JavaScript 中使用 onclick
您可以使用.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
您可以在.onclick函数调用中使用this来在单击时获取按钮元素。

<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>
function whatButton (button) {
  console.log("You clicked button with class " + button.className);
  console.log("You clicked button with text " + button.innerText);
}

3) 使用 addEventListener
这类似于.onclick ,但您可以直接使用this来定位按钮元素。

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'); buttons.forEach(button => { button.addEventListener('click', (event) => { console.log('Clicked on: #id-' + event.target.id); }) })
 <button class="button" id="1">button 1</button> <button class="button" id="2">button 2</button> <button class="button" id="3">button 3</button>

您可以从event.target对象获取任何其他属性。

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

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

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

例如..

 const youClicked = document.querySelector('.you-clicked'); document.querySelector('.buttons') .addEventListener('click',(e) => { //lets only look for the buttons //and not for this div if (e.target.tagName === 'BUTTON') { youClicked.innerText = e.target.innerText; } });
 <div class="buttons"> <button>One</button> <button>Two</button> <button>Three</button> <button>Four</button> <button>Five</button> <button>Six</button> <button>Seven</button> </div> <br> <div> You Clicked => <span class="you-clicked">?</span> <div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM