如何在 JavaScript 中呼叫函式?


函式是一組可重複使用的程式碼,可以在程式中的任意位置呼叫。這避免了重複編寫同一段程式碼。它有助於程式設計師編寫模組化的程式碼。

在 JavaScript 中定義函式的最常見方法是使用 function 關鍵字,然後是唯一的函式名稱、引數列表(可能為空)以及用花括號括起來的一段語句塊。

以下是一個示例 −

<script>
   <!--
      function sayHello() {
         alert("Hello there");
      }
   //-->
</script>

要稍後在指令碼中某個地方呼叫函式,只需寫出該函式的名稱,如下面的程式碼所示。

示例

以下示例展示瞭如何在 JavaScript 中呼叫函式

即時演示

<html>
   <head>
      <script>
         function sayHello() {
         d ocument.write ("Hello there!");
         }
      </script>
   </head>

   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      </form>
      <p>Use different text in write method and then try...</p>
   </body>
</html>

更新於: 2020 年 1 月 9 日

167 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.