我有一個外部的JavaScript文件,有兩個功能,並應在每次頁面加載時調用。 但是,也沒有。如果我在調用tester()函數的js文件中註釋掉該行,則會調用runGame(),但如果tester()未被註釋,則不會運行。但是,如果我在runGame()調用之後放置了tester()函數,那麼runGame()將起作用,但tester()仍然不起作用。爲什麼這兩個函數都沒有被調用,如果其中一個沒有註釋?
tester()甚至不能自行運行,所以有可能是我在那個函數中做錯了。誰能告訴我我做錯了什麼?
HTML
<html>
<head>
<script type="text/javascript" src="rock_paper_scissors.js">
</script>
</head>
<body>
<p id="game">Test</p>
<br />
<input type="button" value="Play again" onClick="tester()"></input>
</body>
rock_paper_scissors.js
var info = document.getElementById("game");
var tester = function(){
document.getElementById('game').innerHTML = 'hello';
//info.innerHTML("HI");
};
var compare = function(choice1, choice2){
if(choice1 == choice2)
document.write("The result is a tie!");
else if(choice1 == "rock"){
if(choice2 == "scissors")
document.write("You win! Rock wins");
else
document.write("The computer wins! Paper wins");
}
else if(choice1 == "paper"){
if(choice2 == "rock")
document.write("You win! Paper wins");
else
document.write("The computer wins! Scissors wins");
}
else if(choice1 == "scissors"){
if(choice2 == "rock")
document.write("The computer wins! Rock wins");
else
document.write("You win! Scissors wins");
}
else
document.write("You didn't pick a real choice");
};
var runGame = function(){
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";
}
document.write("<p>You picked " + userChoice + "</p>");
document.write("<p>The Computer picked " + computerChoice + "</p>");
compare(userChoice, computerChoice);
};
runGame();
tester();
將腳本標記放在主體結束標記後面,以便它僅在加載DOM時加載。 – zz3599 2013-03-27 04:42:59
檢查JavaScript控制檯...您無法在加載之前修改DOM。將''標籤移動到'