我正在尝试用HTML / Javascript创建一个“Magic 8 Ball”。我一直试图摆弄代码,我将继续添加/玩游戏,但如果有人可以提供帮助,我将不胜感激。如果我搞清楚,我会更新帖子,但是我目前仍然处于困境。
程序的重点是用户可以输入问题,然后每当点击8球图像时,其中一个随机答案将出现在8球图像下方。
我认为我的错误在于“response = RandomOneOf .....”行。
<!doctype html>
<!-- =================================================== -->
<html>
<head>
<title> Magic-8 Ball </title>
<script type="text/javascript" src="random.js">
function GenerateAnswer()
{
response = RandomOneOf([
'It is certain',
'Without a doubt',
'Most likely',
'Yes',
'Reply hazy try again',
'Ask again later',
'My reply is no',
'No',
'Very doubtful',
]);
document.getElementById('magicBallButton').onclick = function GenerateAnswer();
document.getElementById('outputDiv').innerHTML =
+ response +;
}
</script>
</head>
<body>
<div style="text-align:center">
<h1>Magic 8-Ball (Mattel, Inc.)</h1>
<br>
Enter a question below, then click on the Magic 8-Ball to recieve its wisdom.
<br>
<input type="text" id="questionBox" size=100 value=''>
<br>
<br>
<input type="image" src="8ball.png" alt="magicBall" id="magicBallButton" onclick="GenerateAnswer()";>
</div>
<div id="outputDiv"> </div>
</body>
</html>
答案 0 :(得分:0)
您的脚本存在许多问题:
<script src>
调用外部脚本,然后在其下方添加内联脚本。外部脚本应具有独立的<script>
标记。GenerateAnswer
#magicBallButton
)时呼叫<input id="magicBallButton" onclick="GenerateAnswer()"
,但也尝试使用document.getElementById('magicBallButton').onclick = function GenerateAnswer();
进行操作。这不仅是多余的,而且您不应在函数唤醒中指定function
。document.getElementById('outputDiv').innerHTML = +response + ;
语法非常无效。您正在寻找document.getElementById('outputDiv').innerHTML = response
。RandomOneOf
数组似乎未定义。您可以使用response = responses[Math.floor(Math.random() * responses.length)];
从数组中获得随机响应。请注意,我删除了原始数组周围的括号,并将其重命名为responses
(因为它包含所有的可能响应,而不仅仅是所需的响应)。这是一个工作示例,纠正了上述所有要点:
function GenerateAnswer() {
responses = [
'It is certain',
'Without a doubt',
'Most likely',
'Yes',
'Reply hazy try again',
'Ask again later',
'My reply is no',
'No',
'Very doubtful',
];
response = responses[Math.floor(Math.random() * responses.length)];
document.getElementById('outputDiv').innerHTML = response;
}
&#13;
<body>
<div style="text-align:center">
<h1>Magic 8-Ball (Mattel, Inc.)</h1>
<br> Enter a question below, then click on the Magic 8-Ball to recieve its wisdom.
<br>
<input type="text" id="questionBox" size=100 value=''>
<br>
<br>
<input type="image" src="8ball.png" alt="magicBall" id="magicBallButton" onclick="GenerateAnswer()" ;>
</div>
<div id="outputDiv"> </div>
</body>
&#13;
希望这有帮助! :)