May 06, 2021 JavaScript
4. JavaScript functions and events
5. JavaScript at . head . . or
6. JavaScript functions in slt;head
The script in HTML must be between the label and the label.
Scripts can be placed in the sections of the HTML page.
To insert JavaScript into an HTML page, use the hashtag.
The JavaScript is told where to start and end.
The line of code between the slt;script> and the slt;/script> contains JavaScript:
You don't need to understand the code above. J ust understand that the browser interprets and executes JavaScript code that is located between the . and
Those older instances may use type"text/javascript" in the hashtag. I t is no longer necessary to do so. JavaScript is the default scripting language for all modern browsers and HTML5. |
In this example, JavaScript writes text to HTML's slt;body at the time the page loads:
The JavaScript statement in the example above is executed when the page loads.
Typically, we need to execute code when an event occurs, such as when a user clicks a button.
If we put JavaScript code into a function, we can call it when an event occurs.
You'll learn more about JavaScript functions and events in a later section.
You can put an unlimited number of scripts in HTML documents.
Scripts can be in the section of HTML, or in both parts.
It is common practice to put the function in the section of slt;head, or at the bottom of the page. This allows them to be placed in the same location without interfering with the content of the page.
In this example, we place a JavaScript function in the section of the HTML page.
The function is called when the button is clicked:
<head>
<script>
function myFunction()
{
Document.getElementByid ("demo"). Innerhtml = "My First JavaScript Function";
}
</script>
</head>
<body>
<h1>我的 Web 页面</h1>
<p id="demo">一个段落</p>
<button type="button" onclick="myFunction()" > Try </ button>
</body>
</html>
In this example, we place a JavaScript function in the section of the HTML page.
The function is called when the button is clicked:
<h1>我的 Web 页面</h1>
<p id="demo">一个段落</p>
<button type="button" onclick=" myFunction() "Try </ Button>
<script>
function myFunction()
{
Document.getElementByid ("demo"). Innerhtml = "My First JavaScript Function";
}
</script>
</body>
</html>
Tip: We put JavaScript at the bottom of the page code so that we can make sure that the script is executed after the element is created.
You can also save the script to an external file. External files typically contain code that is used by multiple Web pages.
The file extension of the external JavaScript file is .js.
To use an external file, set the file in the "src" property of .js label:
You can place the script in the actual effect of writing the script in the slt;head;or in the .lt;body.gt;
The external script cannot contain a label. |