javascript - 如何更改此处的值?
问题描述
我正在创建一个石头、纸、剪刀游戏。我可以在以下位置更改玩家选择player.currentChoice = choices[2];
但是,我还将选择链接到一个 HTML 按钮,一旦单击它应该将其更改player.currentChoice = choices[0];
为显示 0,因为这是摇滚的选择。
如何将主更新player.currentChoice = choices[2];
为player.currentChoice = choices[0];
?我的功能根本不起作用我知道这不是正确的方法。我基本上需要player.currentchoice
外部功能来更新,以触发我的游戏的其余部分。
const player = {
currentChoice: null
}
const computer = {
currentChoice: null
}
const choices = ["Rock", "Paper", "Scissors"];
player.currentChoice = choices[2];
document.getElementById('rock').addEventListener('click', updateRock);
function updateRock(){
player.currentChoice = choices[0];
}
解决方案
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
const player = {
currentChoice: null
}
const computer = {
currentChoice: null
}
const choices = ["Rock", "Paper", "Scissors"];
player.currentChoice = choices[2];
var rockBtn = document.getElementById('rock');
var paprBtn = document.getElementById('paper');
var scirBtn = document.getElementById('scissors');
if(rockBtn || paprBtn || scirBtn) {
rockBtn.addEventListener('click', updateVar);
paprBtn.addEventListener('click', updateVar);
scirBtn.addEventListener('click', updateVar);
}
function updateVar(event){
if(event.target.id == 'rock'){
player.currentChoice = choices[0];
} else if (event.target.id == 'paper'){
player.currentChoice = choices[1];
} else if (event.target.id == 'scissors'){
player.currentChoice = choices[2];
}
console.log(player.currentChoice);
}
推荐阅读
- excel - 我的代码不会删除我试图保留的数据下的不必要数据行
- python - 如何在 Python 3.7 中从 pdf 中提取文本
- javascript - Safari 中的 3rd 方 cookie 不会在 iframe 本身中保留
- android - 以编程方式设置 imageview tint 颜色
- c++ - 文件数据读取到地图,但 map::find() 不起作用
- java - 对象重新初始化:内存分配
- perl - 将单选按钮选择存储为变量 perl cgi 脚本
- python - 正则表达式以识别 Tor 域
- c# - 具有多线程访问的 SQLitePCLRaw.provider.e_sqlite3.dll 中的 System.AccessViolationException 或 System.ExecutionEngineException 崩溃
- javascript - 如何获取我的验证码以生成验证码?