最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get value from the button element that I click - Stack Overflow

programmeradmin2浏览0评论

I have three button in html:

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

In displayResult() function (wrriten once for 3), how can I get value from the button that I click? If I set ids for all 3 button, I have to write 3 display function to get value from a seperate button:

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

I have three button in html:

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

In displayResult() function (wrriten once for 3), how can I get value from the button that I click? If I set ids for all 3 button, I have to write 3 display function to get value from a seperate button:

let displayResultForRock = () => {
  let value = document.getElementById('rock').value;
}
Share Improve this question asked Apr 22, 2022 at 21:06 Duy DuyDuy Duy 6211 gold badge6 silver badges9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Just attach event listeners to the buttons, and then log the textContent of each.

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>

Or use 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>

Please use this code. you can update your displayResult function like this.

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>

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>

why not just pass the value as parameter to the function like this:

<button value="Rock" onclick="displayResult("Rock")">Rock</button>
发布评论

评论列表(0)

  1. 暂无评论