简体   繁体   中英

How do I get my button name to act as my answer for a text input?

I'm currently doing a rock paper scissors game where it should take the button name(rock, paper, or scissors) and use that as the player input.

So far my project takes the player's choice by prompting a text box where I can type the answer and works as expected. Is there a way in javascript where I can take the text from the buttons and convert that into the answer?

Or

 document.querySelectorAll("button").forEach(function(button) { button.addEventListener('click', function(ev) { var value = button.getAttribute("data-type"); console.log("you pressed " + value); }) })
 <button data-type="rock">Rock</button> <button data-type="paper">Paper</button> <button data-type="scissors">Scissors</button>


<button onclick="submit('rock')">Rock</button>
<button onclick="submit('paper')">paper</button>
<button onclick="submit('scissors')">scissors</button>
function submit(answer){
    // there's your answer: answer (it is a local variable)
}

you can easily use this code to get name of button witch you click. i use p tag to show the name of button witch clicked. you can remove it and use the javascript code to youer next use

 function getInfo(event){ document.getElementById('p').innerHTML = event.target.innerHTML }
 <button type="button" onclick="getInfo(event)">Rock</button> <button type="button" onclick="getInfo(event)">paper</button> <button type="button" onclick="getInfo(event)">scissors</button> <p id="p"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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