我剛開始學習javascript,並在codeacademy上進行了一項練習,以製作文本基礎搖滾紙剪刀遊戲。 我想將它展示給調試控制檯之外的某個人,但我無法弄清楚如何在html頁面中顯示它。如何在HTML頁面中顯示返回的值
在我的HTML文件中的代碼是:
<HTML>
<HEAD>
<script src="rockpaperscissors.js"></script>
</HEAD>
<BODY>Choose rock, paper or scissors and write your choice in the text box
<p>
<A HREF="javascript:processOrder();">Click here to begin</A>
</p>
...
</BODY>
</HTML>
,並在我的JS代碼:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function (choice1, choice2) {
if (choice1 === choice2) return "The result is a tie!";
if (choice1 === "rock") {
if (choice2 === "scissors") return "rock wins";
else return "paper wins";
}
if (choice1 === "paper") {
if (choice2 === "rock") return "paper wins";
else return "scissors wins";
}
if (choice1 === "scissors") {
if (choice2 === "rock") return "rock wins";
else return "scissors wins";
}
};
compare(userChoice, computerChoice);
我得到的提示選擇石頭紙或剪刀,但它不返回任何東西之後。我沒有在html中看到計算機的選擇,我不知道用什麼來顯示它。
請注意,函數'compare'並不總是返回結果,這不是一件好事。如果用戶在被要求選擇時按下Cancel,'userChoice'將爲'null',並且該函數不會返回值。 –