試圖創建一個簡單的岩石紙剪刀遊戲。但是,當我點擊submit
我的CalcWinner();
得到一個控制檯錯誤「函數未定義」。Javascript函數返回爲undefined
我敢肯定,我錯過了一些容易,任何建議將不勝感激!
<!DOCTYPE html>
<html lang="en">
<head>
\t <meta charset="UTF-8">
\t <title>Rock - Paper - Scissors</title>
\t <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<p>Click the button to pick rock, paper or scissors.</p>
<input type = "text" id = "picker" />
<button onclick="calcWinner();">Make your Selection?</button>
<!-- <input type = "submit" value="Make your Selection"/> -->
<p id="demo"></p>
<p id="score"></p>
<script>
$(document).ready(function(){
var myChoice = "";
var compChoice = "";
var myScore = 0;
var compScore = 0;
function calcWinner() {
myChoice = document.getElementById("picker");
compChoice = Math.random();
if (compChoice < 0.33) {
compChoice = "rock";
} else if(compChoice < 0.67) {
compChoice = "paper";
} else {
compChoice = "scissors";
}
if (compChoice == myChoice) {
document.getElementById("demo").innerHTML = "It's a tie! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (compChoice == "rock") {
if(myChoice == "scissors") {
\t compScore ++; \t
document.getElementById("demo").innerHTML = "You lose! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (myChoice == "paper") {
userScore ++;
document.getElementById("demo").innerHTML = "You win! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (myChoice == "paper") {
}
} else if (compChoice == "paper") {
if (myChoice == "rock") {
\t compScore ++; \t
document.getElementById("demo").innerHTML = "You lose! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (myChoice == "paper") {
} else if (myChoice == "scissors") {
\t userScore ++;
document.getElementById("demo").innerHTML = "You win! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (myChoice == "paper") {
}
} else if (compChoice == "scissors") {
if (myChoice == "rock") {
\t userScore ++;
document.getElementById("demo").innerHTML = "You win! You picked " + myChoice + " and the computer picked " + compChoice + " you have " + userScore;
} else if (myChoice == "paper") {
} else if (myChoice == "paper") {
\t compScore ++; \t
document.getElementById("demo").innerHTML = "You lose! You picked " + myChoice + " and the computer picked " + compChoice;
} else if (myChoice == "paper") {
}
}
};
});
</script>
不要將'calcWinner'方法包裝在ready函數中。 –
將'calcWinner'移出'ready',它將是_private_並且不能從外部訪問 – Tushar