JavaScript code needs to be placed in the web page using the "<script>" tag and run with the help of the browser environment; the syntax is "<script>JS code</script>" or "".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript programs cannot run independently and can only be executed in the host environment. Under normal circumstances, JavaScript code can be placed in the web page and run with the help of the browser environment.
There are two ways to put JavaScript code into a web page:
Method 1: Use the <script> tag to directly embed the code</script>
Embedding JavaScript scripts in HTML pages requires the use of the <script> tag. Users can directly write JavaScript code in the <script> tag. </script>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>第一个JavaScript程序</title> <script type="text/javascript"> document.write("<h1>Hi,JavaScript!</h1>"); </script> </head> <body></body> </html>
Method 2: Put the JavaScript code into a js file and use the <script> tag to import the js file</strong></p><p> JavaScript programs can be placed not only directly in HTML documents, but also in JavaScript files. </p><p>JavaScript files are text files with the extension <code>.js</code> and can be edited using any text editor. </p><p>JavaScript files cannot run independently and need to be imported into the web page and executed through the browser. JavaScript files can be imported using the <script> tag. </p><p>For example: There is a test.js file that contains the following code: </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false">alert("Hi,JavaScript!");</pre><div class="contentsignin">Copy after login</div></div><p>Insert a <script> tag within the <head> tag of an HTML file. Define the src attribute and set the attribute value to a URL string pointing to an external JavaScript file. The code is as follows: </p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><script type="text/javascript" src="test.js"></script></pre><div class="contentsignin">Copy after login</div></div><blockquote> <p>Note: </p> <p>When using the <script> tag to include external JavaScript files, the default file type is Javascript. Therefore, regardless of whether the loaded file has a .js extension or not, the browser will parse it as a JavaScript script. </script>
The <script> tag that defines the src attribute should no longer contain JavaScript code. If the code is embedded, only the external JavaScript file will be downloaded and executed, and the embedded code will be ignored. </script>
Save the HTML file and preview it in the browser:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of Where to put javascript code. For more information, please follow other related articles on the PHP Chinese website!