如何使用 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>

更新時間: 09-Jan-2020

167 瀏覽量

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.