JS 在哪使用

来源:互联网 发布:梦想小镇mac无限金币 编辑:程序博客网 时间:2024/04/20 01:07

JavaScripts in the body section will be executed WHILE the page loads.
在body中插入的JavaScript在页面加载时会被执行。

JavaScripts in the head section will be executed when CALLED.
在head中插入的JavaScript会在被调用时执行。


Examples
实例

Head section
Head部分
Scripts that contain functions go in the head section of the document. Then we can be sure that the script is loaded before the function is called.
将脚本中的函数插入head部分,这样就可以确保函数在被调用前已经加载完成。

Body section
Body部分
Execute a script that is placed in the body section.
Body部分中的脚本将被直接执行。

External script
外部脚本
How to access an external script.
如何调入外部脚本。


Where to Put the JavaScript
在哪里插入JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
页面中的JavaScripts会在页面被浏览器加载时被执行。但有时候我们想要的并不是这样,或许我们会需要有些脚本在页面加载时执行,也可能希望脚本在用户触发一些时间时执行。

Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
在head部分中的脚本:此部分的脚本会在它们被调用或相应的触发事件发生时被执行。将脚本插入到head部分,可以确保它们被调用时已经加载完全。

<html>

<head>
<script type="text/javascript">
....
</script>
</head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
body部分的脚本:脚本将在页面加载到时被执行。在页面中插入脚本,脚本将伴随页面一起加载。

<html>
<head>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
位于 body 和 head 部分的脚本:你可以在你的文档中放置无限量的脚本程序,因此,你可以在 body 和 head 中放置脚本程序。

<html>
<head>
<script type="text/javascript">
....
</script>
</head> <body> <script type="text/javascript">
....
</script>
</body>


Using an External JavaScript
只用外部的JavaScript

Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page.
有时,你可能需要在多个页面运行一个JavaScript,但希望不要在每个页面上都书写一边相同的脚本程序。

To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.
为了简化上述情况,你可以将JavaScript写在一个外部文件中,并将其保存为一个以.js为扩展名的外部 JavaScript 文件。

Note: The external script cannot contain the <script> tag!
注意:外部的脚本不能包含<script>标签。

To use the external script, point to the .js file in the "src" attribute of the <script> tag:
你可以在<script>标签中使用src书写指定扩展名为.js的外部JS脚本,具体如下:

<html>
<head>
<script src="xxx.js"></script> </head> <body> </body> </html>

Note: Remember to place the script exactly where you normally would write the script!
注意:记住,请将 script 脚本程序准确防置在你习惯书写脚本的位置。

 
原创粉丝点击