[英]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? javascript 中是否有一种方法可以从按钮中获取文本并将其转换为答案?
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.我使用 p 标签来显示按钮女巫点击的名称。 you can remove it and use the javascript code to youer next use您可以将其删除并使用 javascript 代码供您下次使用
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.