HTML 中的內聯 JavaScript 如何工作?


在本文中,您將瞭解內聯 JavaScript 如何與 HTML 一起工作。內聯 JavaScript 表示在 html 檔案中的 <script> 標籤之間編寫的程式碼塊。在 HTML 檔案中使用內聯 JavaScript 的優點是減少 Web 瀏覽器到伺服器的往返次數。

示例 1

讓我們瞭解如何在 html 檔案中使用內聯 JavaScript 新增基本語句 -

<!DOCTYPE html >
<html>
<head>
   <h2> This is a simple HTML file</h2>
   <script>
      document.write("Hi, This is an inline Javascript code written in between script tags");
   </script>
</head>
</html>

解釋

  • 步驟 1 - 在一個簡單的 html 檔案中,新增一個標題標籤 <h2> 並顯示您選擇的標題。

  • 步驟 2 - 在標題標籤下方新增一個指令碼標籤 <script>。

  • 步驟 3 - 在指令碼標籤中,使用 document.write() 函式列印文字。

示例 2

在本例中,讓我們使用內聯 javascript 在 html 檔案中列印一個數組。

<!DOCTYPE html >
<html>
<head>
   <h2> This is a simple HTML file</h2>
   <script>
      document.write("An Inline Javascript code to display an array")
      document.write("<br>")
      const inputArray = [3,4,5,6,7,8]
      document.write("
The array is defined as :", inputArray) </script> </head> </html>

解釋

  • 步驟 1 - 在一個簡單的 html 檔案中,新增一個標題標籤 <h2> 並顯示您選擇的標題。

  • 步驟 2 - 在標題標籤下方新增一個指令碼標籤 <script>。

  • 步驟 3 - 在指令碼標籤中,定義一個名為 inputArray 的陣列,並將數值新增到陣列中。

  • 步驟 4 - 使用 document.write() 函式列印陣列。

更新於: 2023-02-16

6K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告