標籤:
HTML 中的指令碼必須位於 <script> 與 </script> 標籤之間。
指令碼可被放置在 HTML 頁面的 <body> 和 <head> 部分中。
JavaScript 函數和事件
上面例子中的 JavaScript 語句,會在頁面載入時執行。
通常,我們需要在某個事件發生時執行代碼,比如當使用者點擊按鈕時。
如果我們把 JavaScript 代碼放入函數中,就可以在事件發生時調用該函數。
您將在稍後的章節學到更多有關 JavaScript 函數和事件的知識。
<head> 或 <body> 中的 JavaScript
可以在 HTML 文檔中放入不限數量的指令碼。
指令碼可位於 HTML 的 <body> 或 <head> 部分中,或者同時存在於兩個部分中。
通常的做法是把函數放入 <head> 部分中,或者放在頁面底部。這樣就可以把它們安置到同一處位置,不會干擾頁面的內容。
body 中的 JavaScript 函數
<!--注意
innerHTML="My First JavaScript Function 不能寫成innerHTML("My First JavaScript Function");
<button type="button" onclick="myFunction()">Try it</button> 這行代碼不能放在<script>標籤中
否則不生效-
-->
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
<head>
</head>
<body>
<center>
<h1>This is a Java Script Page</h1>
<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>
</html>
-----------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<head>
<title></title>
</head>
<center>
<body>
<script>
document.write("<h1>This is my first Java Script</h1>");
document.write("<p>Come with me!</p>");
</script>
</body>
</center>
</html>
-----------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
head 中的 JavaScript 函數
<!--
<head> 中的 JavaScript 函數
在本例中,我們把一個 JavaScript 函數放置到 HTML 頁面的 <head> 部分。
該函數會在點擊按鈕時被調用:
-->
<!--<button type="button" onclick="myFunction()">Try it</button>
在函數調用的過程中將函數的名稱寫錯
-->
<!DOCTYPE html>
<html>
<center>
<meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</center>
</html>
JavaScript-body 中的 JavaScript 函數\head 中的 JavaScript 函數