gpt4 book ai didi

javascript - 将外部 JS 文件包含到 HTML 中

转载 作者:行者123 更新时间:2023-11-30 09:45:15 25 4
gpt4 key购买 nike

我们有一个任务,我需要在 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文件在同一个目录下。

最佳答案

应该是这样

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

不是

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

当你引用 '/' 时,它往往会说,在根目录中查找文件。如果文件与 html 中的文件位于同一文件夹中,则无需使用“/”。

关于javascript - 将外部 JS 文件包含到 HTML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com