将外部JS文件包含在HTML

时间:2016-08-24 19:25:01

标签: javascript 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文件都在同一目录中。

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

1 个答案:

答案 0 :(得分:4)

IT应该是这个

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

angular.module('myApp', ['ngRoute'])

.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/home', {
            templateUrl: 'views/home.html'
        })
        .when('/directory', {
            templateUrl: 'views/directory.html',
            //since this page requires a controller
            controller: 'myController'
        })
        .otherwise({
            redirectTo: '/home'
        });

}]);

angular.module('myApp', [])
   .controller('myController', function($scope) {
      $scope.message = ("Hello World");
});

当你提供'/'时,它倾向于说,在根目录中查找文件。如果文件与html中的文件夹相同,则无需使用'/'。