如何在 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>
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP