JavaScript functions and events (onclick /)

JavaScript functions and events

In general, we need to execute code when an event occurs, such as when the user clicks the button.

If we put JavaScript code in the function, you can call this function when the event occurs.

The <head> or <body> of JavaScript

You can put in an unlimited number of scripts in an HTML document.

HTML scripts may be located in the <body> or <head> section, or exist in two portions.

The usual practice is to function into the <head> section, or on the bottom of the page. So that they can be placed into the same position, it does not interfere with the content of the page.

<Head> JavaScript functions

In this example, we placed a JavaScript function HTML page <head> section.

This function is called when the button is clicked:

<! DOCTYPE HTML > 
< HTML > 
< head > 
< Script > 
function myFunction () 
{ 
    document.getElementById ( " Demo " ) .innerHTML = " My first JavaScript function " ; 
} 
</ Script > 
</ head > 

< body > 
< h1 > my Web page </ h1 > 
< the p- the above mentioned id = "Demo" > paragraph </p>
<button type="button" onclick="myFunction()">尝试一下</button>
</body>

</html>

<Body> JavaScript functions

In this example, we placed a JavaScript function <body> part of the HTML page.

This function is called when the button is clicked:

<!DOCTYPE html>
<html>

<body>

    <h1>我的 Web 页面</h1>
    <p id="demo">一个段落</p>
    <button type="button" onclick="myFunction()">尝试一下</button>
    <script>
        function myFunction(){
        document.getElementById("demo").innerHTML="My first JavaScript function " ; 
        } 
    </ Script > 

</ body > 

</ HTML >        

 

Guess you like

Origin www.cnblogs.com/gengyufei/p/12590904.html