【发布时间】:2021-04-21 13:42:18
【问题描述】:
我对编程很陌生,我正在尝试使用 Javascript 制作石头剪刀布,但遇到了这个问题。每当我单击岩石图像时,它应该会生成一个介于 0 和 2 之间的随机数,如果数字为 0,则为平局,如果为 1,则玩家输,如果为 2,则玩家获胜。但是当我运行此代码时,它仅在数字为 0 时才有效。因此,当我单击按钮时,如果数字为 0,则显示“它是平局”,但如果不是 0,则不显示任何内容。但是当我再次尝试点击时,它不起作用。我必须刷新页面再试一次。谁能帮助我,如果我没有正确解释这一点,请见谅。
HTML:
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet">
</head>
<title> Rock Paper Scissors! </title>
<body>
<div id="rpsGame">
<h1 id="RPS"> Rock, paper, scissors! </h1>
<div id="score">
<p id="myScore">0</p>
<p>:</p>
<p id="botScore">0</p>
</div>
<img src="rock.png" id="rock">
<img src="paper.png" id="paper">
<img src="scissors.png" id="scissors">
<p id="winOrLose"></p>
</div>
</body>
</html>
Javascript:
var randomNumber = Math.floor(Math.random() * 3)
var rockChoice = document.getElementById('rock');
var botAnswer = document.getElementById('winOrLose')
rockChoice.addEventListener('click', function() {
if (randomNumber == 0) {
botAnswer.textContent = "Bot picked rock, you tie!"
if (randomNumber == 1) {
botAnswer.textContent = "Bot picked paper, you lose!"
if (randomNumber == 2) {
botAnswer.textContent = "Bot picked scissors, you lose!"
}
}
}
});
CSS:
body {
background-color:#2a303d;
text-align: center;
font-family: 'Ubuntu', sans-serif;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
#rock {
width: 80%;
position: absolute;
top: 45.8%;
left: 39.75%;
transform: translate(-50%, -50%);
transform: rotate(360deg);
height: 100px;
width: 100px
}
#paper {
width: 80%;
position: absolute;
top: 45.8%;
left: 46.75%;
transform: translate(-50%, -50%);
transform: rotate(360deg);
height: 100px;
width: 100px;
}
#scissors {
width: 80%;
position: absolute;
top: 52.05%;
left: 57.25%;
transform: translate(-50%, -50%);
height: 100px;
width: 100px;
}
#RPS {
font-size: 65px;
margin-top: 40px;
}
#botPick {
font-size: 50px;
margin-top: 350px;
}
#Score p {
margin:0;
padding:0;
margin-left: 5px;
font-size: 36px;
display: inline-block;
line-height: 80px;
vertical-align: top;
}
#winOrLose {
color: white;
}
【问题讨论】:
-
你正在嵌套你的 ifs,所以代码只对第一个 ===0 作出反应,没有其他反应,将其他人移到第一个 if 之外,请了解 esle if 的工作原理:@ 987654321@
-
哦,哇,我很笨。我其实不是故意的,但是谢谢。现在唯一的问题是我必须刷新页面并再次单击按钮才能再次执行此操作。如果我再次点击它而不刷新它就不会工作。
-
在第一个 if 之前将您的随机数声明移动到 click EventListener 中,因此每次单击时都会生成新的随机数,就像您现在拥有的方式一样,它会在加载时生成一次并保持不变.
-
不错!非常感谢。它奏效了。
-
作为旁注:读入
switch statement。 In 消耗的资源少于在您的案例中优化代码的 if 语句。
标签: javascript html css dom-events addeventlistener