繁体   English   中英

将外部JS文件包含到HTML中

[英]include an external JS file into HTML

我正在尝试学习JavaScript(从Coursera)。 在您否决我之前,请注意我是JavaScript新手。 我们有一项作业,我需要在html中插入外部javascript文件。

HTML文件

 <!DOCTYPE html>
 <title>Color Guessing Game</title>
 <body onload="do_game()">
      <script type="text/javascript" src="/colguess.js"></script>
 </body>
 </html>

JS文件

var guess_input_color;
var finished=false;
var colors=["blue","cyan","gold","gray","green","magenta","red","white","yellow"];
var guesses=0;
function do_game(){
  var n=Math.floor(Math.random()*9);
  var color=colors[n];
  while(!finished){
    guess_input_color=prompt("i am thinking of one of these colors:\n\n"+colors+"\n\nWhat color am i thinking of?");
    ++guesses;
    finished=check_guess();
  }
}
function check_guess(){
  if(colors.indexOf(guess_input_color)==-1)
   {
     alert("Sorry, i don't recognize your color.\n\nPlease try again.");
     return false;
   }
  if(color>guess_input_color){
        alert("Sorry, your guess is not correct!\n\nHint:your color is alphabetically lesser than mine\n\nPlease try again.");
         return false;
    }
   if(color<guess_input_color){
        alert("Sorry, your guess is not correct!\n\nHint:your color is alphabetically higher than mine\n\nPlease try again.");
        return false;
    }
    document.body.style.backgroundColor = guess_input_color;
    document.body.style.backgroundColor = guess_input_color;
    alert("Congratulations! You have guessed the color!\n\nIt took you"+guesses+" guesses to finish the game!\n\n")
    return true;
   }

注意:html和js文件都在同一目录中。

我不确定错误在哪里。 请帮助我解决问题。

IT应该是这个

<script type="text/javascript" src="colguess.js"></script>

<script type="text/javascript" src="/colguess.js"></script>

当您引用“ /”时,通常会说是在根目录中查找文件。 如果文件与html位于同一文件夹中,则无需使用“ /”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM