从我单击的按钮元素中获取值

get value from the button element that I click

我在 html 中有三个按钮:

<button value="Rock" onclick="displayResult()">Rock</button>
<button value="Paper" onclick="displayResult()">Paper</button>
<button value="Scissors" onclick="displayResult()">Scissors</button>

displayResult()函数中(3次写一次),如何从我点击的按钮中获取值?如果我为所有 3 个按钮设置 id,我必须编写 3 个显示函数以从单独的按钮获取值:

let displayResultForRock = () => {
  let value = document.getElementById('rock').value;
}

const btns = document.querySelectorAll("button")
btns.forEach(b => b.onclick = e => result.innerText = e.target.value)
<button value="Rock">Rock</button>
<button value="Paper">Paper</button>
<button value="Scissors">Scissors</button>
<div id="result"></div>

请使用此代码。您可以像这样更新 displayResult 函数。

function displayResult(event) {
  console.log(event.target.value)
}
<button value="Rock" onclick="displayResult(event)">Rock</button>
<button value="Paper" onclick="displayResult(event)">Paper</button>
<button value="Scissors" onclick="displayResult(event)">Scissors</button>

为什么不像这样将值作为参数传递给函数:

<button value="Rock" onclick="displayResult("Rock")">Rock</button>

只需将事件侦听器附加到按钮,然后记录每个按钮的 textContent

const buttons = document.querySelectorAll('button');

buttons.forEach(button => {
  button.addEventListener('click', handleClick, false);
});

function handleClick() {
  console.log(this.textContent);
}
<button>Rock</button>
<button>Paper</button>
<button>Scissors</button>

或使用event delegation:

const buttons = document.querySelector('#buttons');

buttons.addEventListener('click', handleClick, false);

function handleClick(e) {
  if (e.target.matches('button')) {
    console.log(e.target.textContent);
  }
}
<div id="buttons">
  <button>Rock</button>
  <button>Paper</button>
  <button>Scissors</button>
</div>