w3pop.com :: ÍøÂçѧԺ :: JavaScript :: JS ÔÚÄÄʹÓÃ
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»áÔÚ±»µ÷ÓÃʱִÐС£
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.
ÈçºÎµ÷ÈëÍⲿ½Å±¾¡£
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²¿·ÖÖеĽű¾£º´Ë²¿·ÖµÄ½Å±¾»áÔÚËüÃDZ»µ÷ÓûòÏàÓ¦µÄ´¥·¢Ê¼þ·¢Éúʱ±»Ö´ÐС£½«½Å±¾²åÈëµ½head²¿·Ö£¬¿ÉÒÔÈ·±£ËüÃDZ»µ÷ÓÃʱÒѾ¼ÓÔØÍêÈ«¡£
<html> |
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> |
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> |
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> |
Note: Remember to place the script exactly where you normally would write the script!
×¢Ò⣺¼Çס£¬Ç뽫 script ½Å±¾³ÌÐò׼ȷ·ÅÖÃÔÚÄãϰ¹ßÊéд½Å±¾µÄλÖá£