我需要創建一個魔術8球網頁,當輸入問題時他們會產生一個隨機響應,然後他們點擊按鈕。到目前爲止,我有HTML和CSS來完成:如何生成一個隨機數並將其分配給JavaScript中的變量數組?
$(document).ready(function() {
$("button").click(function() {
var answer;
var my_num = getRandom(14);
var responses = Array(15);
responses[0] = "Ask again later...";
responses[1] = "Yes";
responses[2] = "No";
responses[3] = "It appears to be so";
responses[4] = "Reply is hazy, please try again";
responses[5] = "Yes, definitely";
responses[6] = "What is it you really want to know?";
responses[7] = "Outlook is good";
responses[8] = "My sources say no";
responses[9] = "Signs point to yes";
responses[10] = "Don't count on it";
responses[11] = "Cannot predict now";
responses[12] = "As I see it, yes";
responses[13] = "Better not tell you now";
responses[14] = "Concentrate and ask again";
var RandNum = Math.floor(Math.random() * 14);
var answer = responses[RandNum];
$("#Response").replaceWith(answer);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Magic 8 Ball</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<header>
<h1>Magic 8 Ball</h1>
</header>
<h3>What would you like to know?</h3>
<input type="text" name="txtQuestion" id="txtQuestion">
<br />
<input type="button" id="btnAsk" value="Ask the 8 Ball">
<h3>The 8 Ball says:</h3>
<h3 id="Response">Ask the 8 Ball a question...</h3>
</div>
<script src="scripts/jquery-3.2.1.js"></script>
<script src="scripts/my_scripts.js"></script>
</body>
</html>
我一直在JavaScript中,但沒有我這樣做似乎產生什麼!這裏是我的代碼:
我真的不知道我做錯了什麼。我認爲我應該創建一個新的陣列,並提供所有可能的響應。然後我生成一個隨機數,並將其分配給數組變量以給我一個隨機響應。然後我用隨機生成的響應替換了存在的h3標籤。理論上聽起來不錯。然而,當我點擊按鈕時沒有任何作用。即使我手動分配一個響應,比如answer = respond [5],也沒有任何反應。我在這裏錯過了什麼?
有沒有'getRandom()'函數。 – Barmar
謝謝巴爾瑪!你會得到贊成! – nponinski