我有一个外部的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。将''标签移动到'