我希望代碼獲取用戶在輸入字段中輸入的值,並將其傳遞給變量userChoice。我不知道爲什麼這段代碼不工作,唯一的學習方法是問你們。Javascript岩石,紙,剪刀遊戲。我的代碼有什麼問題?
HTML:
<h3> Choose your destiny !</h3>
<form>
<input type="text" id="form" />
<input type="button" id="button" value="Click Me!" onclick="clickMe();" />
</form>
的JavaScript:
var computerChoice = Math.random();
var userChoice = "";
function clickMe() {
document.getElementById("form").value === userChoice;
}
if (computerChoice < 0.33) {
computerChoice = "rock";
};
if (computerChoice < 0.66) {
computerChoice = "paper";
};
if (computerChoice < 1) {
computerChoice = "scissors";
};
if (userChoice === "rock" && computerChoice === "rock") {
alert("It's a tie!");
} else if (userChoice === "rock" && computerChoice === "paper") {
alert("Computer Wins!");
} else if (userChoice === "rock" && computerChoice === "scissors") {
alert("You WIN!");
};
if (userChoice === "paper" && computerChoice === "rock") {
alert("You WIN!");
} else if (userChoice === "paper" && computerChoice === "paper") {
alert("It's a TIE!");
} else if (userChoice === "paper" && computerChoice === "scissors") {
alert("Computer Wins!");
};
if (userChoice === "scissors" && computerChoice === "rock") {
alert("Computer Wins!");
} else if (userChoice === "scissors" && computerChoice === "paper") {
alert("You WIN!");
} else if (userChoice === "scissors" && computerChoice === "scissors") {
alert("It's a TIE!");
};
的jsfiddle?幫助我來幫助你 – ne1410s 2014-09-25 21:25:57
兩個快速問題:只有一次 - 當頁面加載時,你只能獲得一個隨機的計算機選擇值。其餘的邏輯在頁面加載時也運行一個 - 它需要爲每次點擊觸發。 – dc5 2014-09-25 21:26:49
computerChoice將始終是「剪刀」,因爲Math.random()總是小於1,它是最後一個條件。您應該對其重新排序1.「<1」2.「<0.66」3.「<0.33」 – 2014-09-25 21:35:47