将外部JS文件包含到HTML中 [英] include an external JS file into HTML

查看:111
本文介绍了将外部JS文件包含到HTML中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习javascript(来自coursera)。在你让我失望之前,请注意,我是javascript中的新手。我们有一个任务,我需要在HTML中插入一个外部javascript文件。

I am trying to learn javascript (from coursera). Before you downvote me to hell, please note that i am newbie in javascript. We have an assignment where i need to insert an external javascript file in a html.

HTML文件
$ b

HTML File

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

JS文件

JS File

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文件都在同一个目录中。

Note: both html and js files are in the same directory.

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

I'm not sure where is the error. Please help me in resolving the issue.

推荐答案

IT应该是这个

IT should be this

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

不是

not

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

当您重写'/'时,往往会说,将文件查找到根目录。如果文件与html中的文件夹在同一文件夹中,则不需要使用'/'。

When you reffer '/', it tends to say, looking for the file into the root directory. if files are in the same folder as in html, then no need to use '/'.

这篇关于将外部JS文件包含到HTML中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆