JavaScript-body 中的 JavaScript 函数\head 中的 JavaScript 函数



HTML 中的脚本必须位于 <script> 与 </script> 标签之间。

脚本可被放置在 HTML 页面的 <body> 和 <head> 部分中。



JavaScript 函数和事件

上面例子中的 JavaScript 语句,会在页面加载时执行。

通常,我们需要在某个事件发生时执行代码,比如当用户点击按钮时。

如果我们把 JavaScript 代码放入函数中,就可以在事件发生时调用该函数。

您将在稍后的章节学到更多有关 JavaScript 函数和事件的知识。




<head> 或 <body> 中的 JavaScript

可以在 HTML 文档中放入不限数量的脚本。

脚本可位于 HTML 的 <body> 或 <head> 部分中,或者同时存在于两个部分中。

通常的做法是把函数放入 <head> 部分中,或者放在页面底部。这样就可以把它们安置到同一处位置,不会干扰页面的内容。



body 中的 JavaScript 函数

<!--注意
innerHTML="My First JavaScript Function 不能写成innerHTML("My First JavaScript Function");
<button type="button" οnclick="myFunction()">Try it</button> 这行代码不能放在<script>标签中
否则不生效-
-->

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
<head>

</head>
<body>
<center>
    <h1>This is a Java Script Page</h1>
    <p id="demo">Hello Java Script</p>
    <script>
    function myFunction()
    {
        document.getElementById("demo").innerHTML="My First JavaScript Function";
    }

    </script>
    <button type="button" οnclick="myFunction()">Try it</button>
</center>

</body>

</html>

-----------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------


<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<head>
    <title></title>
</head>
<center>
<body>

<script>
    document.write("<h1>This is my first Java Script</h1>");
    document.write("<p>Come with me!</p>");
</script>

</body>
</center>
</html>

-----------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------

head 中的 JavaScript 函数

<!--
<head> 中的 JavaScript 函数

在本例中,我们把一个 JavaScript 函数放置到 HTML 页面的 <head> 部分。

该函数会在点击按钮时被调用:
-->
<!--<button type="button" οnclick="myFunction()">Try it</button>
在函数调用的过程中将函数的名称写错
-->
<!DOCTYPE html>
<html>
<center>
<meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
<head>
    <script>
    function myFunction()
    {
        document.getElementById("demo").innerHTML="My First JavaScript Function";
    }
    </script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>

<button type="button" οnclick="myFunction()">Try it</button>
</body>
</center>
</html>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值