The script in the HTML must be between the <script> and </script> tags.
The script can be placed in the <body> and
JavaScript Functions and Events
The JavaScript statements in the example above will be executed when the page loads.
In general, we need to execute code when an event occurs, such as when a user taps a button.
If we put JavaScript code in a function, we can call it when the event occurs.
You'll learn more about JavaScript functions and events in a later chapter.
JavaScript in
An unlimited number of scripts can be placed in an HTML document.
The script can be in the <body> or
It is common practice to put functions in the
JavaScript functions in the body
<!--note
Innerhtml= "My first JavaScript function cannot be written as InnerHTML (" My first JavaScript function ");
<button type= "button" onclick= "MyFunction ()" >try it</button> This line of code cannot be placed in the <script> tag
Otherwise does not take effect-
-
<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html charset=utf-8"/>
<body>
<center>
<p id= "Demo" >hello Java script</p>
<script>
function MyFunction ()
{
document.getElementById ("Demo"). Innerhtml= "My first JavaScript Function";
}
</script>
<button type= "button" onclick= "MyFunction ()" >try it</button>
</center>
</body>
--------------------------------------------------------------------------------------------------------------- --------
--------------------------------------------------------------------------------------------------------------- --------
<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title></title>
<center>
<body>
<script>
document.write ("document.write ("<p>come with me!</p>");
</script>
</body>
</center>
--------------------------------------------------------------------------------------------------------------- --------
--------------------------------------------------------------------------------------------------------------- --------
JavaScript functions in the head
<!--
JavaScript functions in
In this example, we put a JavaScript function in the
The function is called when the button is clicked:
-
<!--<button type= "button" onclick= "MyFunction ()" >try it</button>
The name of the function is incorrectly written during a function call
-
<! DOCTYPE html>
<center>
<meta http-equiv= "Content-type" content= "text/html charset=utf-8"/>
<script>
function MyFunction ()
{
document.getElementById ("Demo"). Innerhtml= "My first JavaScript Function";
}
</script>
<body>
<p id= "Demo" >a paragraph</p>
<button type= "button" onclick= "MyFunction ()" >try it</button>
</body>
</center>
JavaScript functions in the
javascript-body JavaScript function \head