javascript
JavaScript代码在哪里放置?
In an HTML code, JavaScript can be placed at three places...
在HTML代碼中,JavaScript可以放在三個位置...
Between the <head>...</head> tag
在<head> ... </ head>標記之間
Between the <body>...</body> tag
在<body> ... </ body>標記之間
In the external file with an extension ".js"
在擴展名為“ .js”的外部文件中
在<head> ... </ head>和<body> ... </ body>標記之間 (Between the <head>...</head> and <body>...</body> tags)
If we want to place a JavaScript code in an HTML file, we can place either in <head>...</head> tag or <body>...</body> tag.
如果要在HTML文件中放置JavaScript代碼,則可以將其放置在<head> ... </ head>標記或<body> ... </ body>標記中。
Syntax:
句法:
<script type="text/javascript">//js code </script>Example:
例:
<html> <head><title>JavaScipt Example</title><script type="text/javascript">//function to add two numbersfunction sum(a, b){return (a+b);}</script> </head><body><script type="text/javascript">//function to subtract two numbersfunction sub(a, b){return (a-b);}</script><p>Here, we are printing sum & sum...</p><p id="result1"></p><p id="result2"></p><script type="text/javascript">//calling functions & printing the valuesdocument.getElementById("result1").innerHTML = "sum = " + sum(10,20);document.getElementById("result2").innerHTML = "sub = " + sub(10,20);</script> </body> </html>Output:
輸出:
Here, we are printing sum & sum...sum = 30sub = -10在擴展名為“ .js”的外部文件中 (In the external file with an extension ".js")
We can also write JavaScript code in an external file, and import the file in an HTML file.
我們還可以在外部文件中編寫JavaScript代碼,并在HTML文件中導入文件。
Syntax to import JavaScript file in an HTML file:
在HTML文件中導入JavaScript文件的語法:
<script src="file_name.js"></script>Example:
例:
JavaScript file (functions.js)
JavaScript文件(functions.js)
//function to add two numbers function sum(a, b){return (a+b); }//function to subtract two numbers function sub(a, b){return (a-b); }HTML file
HTML文件
<html> <head><title>JavaScipt Example</title><script src="functions.js"></script> </head><body><p>Here, we are printing sum & sum...</p><p id="result1"></p><p id="result2"></p><script type="text/javascript">//calling functions & printing the valuesdocument.getElementById("result1").innerHTML = "sum = " + sum(10,20);document.getElementById("result2").innerHTML = "sub = " + sub(10,20);</script> </body> </html>Output:
輸出:
Here, we are printing sum & sum...sum = 30sub = -10翻譯自: https://www.includehelp.com/code-snippets/where-to-place-javascript-code.aspx
總結
以上是生活随笔為你收集整理的JavaScript代码在哪里放置?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P3386 【模板】二分图匹配(匈牙利模
- 下一篇: 无参有参构造函数