How to embed javascript in HTML

  
There are three ways to embed client-side JS code in HTML documents: 1. Internally placed between the <script> and </script> tags 2. External references refer to JS files outside the HTML file. This way the code is more clear. The method is to put the JS file The 3 inline reference to the head tag is achieved through the event attribute in the HTML tag. Take the first method of internal reference as an example
    <!DOCTYPE. html>            
    <html>                             
    <head>                             
    <title>Digital clock</title>  
    <script> //js code  
    //Define a function to display the time  
    function displayTime(){  
        var elt=document.getElementById('clock') //find element by id 'clock'  
        var now = new Date() //Get the current time  
        elt.innerHTML = now//Let elt display  
        setTimeout(displayTime,1000) //execute again after one thousand milliseconds, which is one second  
    }  
    window.onload=displayTime //Start display time when onload event occurs  
    </script>  
<body>
	<div id='clock'></div>

</body>
   <style> //Clock style#cloock{ //Define the style of the element with id='CLOCK'fount:bold 24pt sans //Use bold large characters background:#ddf //Define blue-gray background padding:10px // There is a circle of blank border: solid black 2px //Define a pure black border border-radius:10px //Define rounded corners (some browsers do not support) } The benefits of using external references
Square mark viewing and maintenance are safer, can be compressed and can encrypt a single JS The file browser can cache JS files to reduce bandwidth usage. Loading JavaScript files by referencing HTML files can make HTML code more concise  
<head>

  <script type="text/javascript" src=ga.js"></script>

  </head>
The method is to put JavaScript files in the head of some uncritical JavaScript files, which can be placed at the bottom of the HTML file to improve the speed of web page access.
<script type="text/javascript" src="ga.js"></script>

  </body>

  </html>

3 Inline references

<input type="button" value="" onclick="alert('Inline reference calls JavaScript code');">
  Differences between HTML5 files and HTML files  
html:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

 

html5:<!doctype html>
   

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326850023&siteId=291194637