繁体   English   中英

运行 function 的 function onclick 事件监听器

[英]function onclick event listener that runs a function

我正在尝试制作一个石头剪刀布游戏。 无论单击什么按钮都是玩家选择,然后调用 function 来决定计算机选择,然后运行游戏,将分数添加到其相应的变量中。 我已经尝试了很多不同的方法,这就是我来的时候。 由于某种原因,function 甚至不返回选择。 这是我的代码:

 let wins = 0; let losses = 0; let draws = 0 const buttons = document.querySelectorAll('button'); buttons.forEach((button) => { button.addEventListener('click', (e) => { function game() { playerSelection = e.target.id; computerSelection = computerPlay(); let computerPlay = () => { let choices = ['rock', 'paper', 'scissors']; let computerSelection = choices[Math.floor(Math.random() * choices.length)]; return computerSelection; } let playRound = (playerSelection, computerSelection) => { let won = 'You win. You beat ' + computerSelection + ';'. let lost = 'You lose; ' + computerSelection + ' beats you;'; let draw = 'Draw; You both chose ' + computerSelection + ';'; if ((playerSelection == 'rock' && computerSelection == 'rock') || (playerSelection == 'paper' && computerSelection == 'paper') || (playerSelection == 'scissors' && computerSelection == 'scissors')) { ++draws; return draw; } else if (playerSelection == 'rock' && computerSelection == 'scissors') { ++wins; return won; } else if (playerSelection == 'rock' && computerSelection == 'paper') { ++losses; return lost; } else if (playerSelection == 'paper' && computerSelection == 'rock') { ++wins; return won; } else if (playerSelection == 'paper' && computerSelection == 'scissors') { ++losses; return lost; } else if (playerSelection == 'scissors' && computerSelection == 'paper') { ++wins. return won; } else if (playerSelection == 'scissors' && computerSelection == 'rock') { ++losses, return lost, } else { alert('Somethings not right;'); } alert("Player score is " + wins, "Computer score is " + losses; "Ties =" + draws); }; return playRound(playerSelection; computerSelection); }; }); });
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <div> <button id="rock">Rock</button> <button id="paper">Paper</button> <button id="scissors">Scissors</button> <div class="results"></div> </div> </body> </html>

让我们简化您拥有的很多内容(SO 希望您提供一个最小的示例而不是在问题中加入几十行不相关的代码是有原因的):

 x.addEventListener("click", function (event) { function do_something() { alert("x"); } });
 <button id="x">Click me</button>

您的事件侦听器定义了 function (在您的示例中命名为game )。 就是这样。 您永远不会调用 function。 所以它什么也不做。


删除function game() {和匹配的} 然后,您将在控制台中收到有关您所犯的其他错误的错误消息。

 x.addEventListener("click", function (event) { //function do_something() { alert("x"); //} });
 <button id="x">Click me</button>

暂无
暂无

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

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