功能标签似乎不起作用?

时间:2014-01-07 11:58:37

标签: javascript html

我正在尝试用Javascript格式编写一个简单的“选择你自己的冒险”风格的游戏,主要是因为它的编写简单,但我遇到了一个问题。我试图让javascript在页面加载时运行,但它不会启动。我只剩下一张空白页。

以下是代码:

<!doctype html>
<body>
<title>Dungeons and Dwarves</title>
<script type="text/javascript>
    function begin() {
    alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
    var myAge = prompt("How old are you, adventurer?")
    if (myAge < 18)
    {
        alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
    }
    else
    {
        alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
    }
}
</script>
<body onload='javascript:begin()'>
</body>

我不确定我在这里做错了什么,但我认为功能标签不能正常工作。就像它在Notepad ++中的样子一样,这可能只是我。有人可以给我帮助吗?

如果我格式化了这个错误,我道歉。

5 个答案:

答案 0 :(得分:4)

浏览器认为您的JavaScript不是JavaScript(但是其他一些未知类型的脚本):

<script type="text/javascript>

您从type属性中省略了第二个"

从HTML 5开始,如果您使用的是JavaScript,则可以省略type属性,所以只需写一下:

<script>

此外,您还有两个<body>开始标记。其中只有一个具有onload属性。浏览器可以解析第一个,然后忽略第二个。


这些(在其他一些错误中)会由validator获取。

答案 1 :(得分:3)

您忘记了"

<script type="text/javascript>

确保将"放在>

前面
<script type="text/javascript">

作为Quentin notes,您有两个body标记。

答案 2 :(得分:0)

type="text/javascript" //add a " at the end

校正

<script type="text/javascript">

答案 3 :(得分:0)

试试这个:

<html>
<head>
<title>Dungeons and Dwarves</title>
<script>
function begin()
{
    alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
    var myAge = prompt("How old are you, adventurer?")
    if (myAge < 18)
    {
        alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
    }
    else
    {
    alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
    }
}
</script>
</head>
<body onload='javascript:begin()'></body>
</html>

您错过了"

<script type="text/javascript>

您错放了第2行的<body>标记:从那里删除了正文标记。

您需要在<title>代码中添加<head>代码。

答案 4 :(得分:0)

<script type="text/javascript> 

将是   <script type="text/javascript">

<body onload='javascript:begin()'></body> 将是  <body onload='javascript:begin();'></body>

所有提醒都需要像

一样结束

var myAge = prompt("How old are you, adventurer?");