當我使用‘onclick’ JavaScript 時如何執行兩個或多個函式?


我們先設定一個按鈕 −

<button type="submit" onclick="callTwoOtherFunctions()"> Call </button>

上面,我們設定了一個“onclick”下的函式,以呼叫其他兩個函式 −

function callTwoOtherFunctions(){
   fun1();
   fun2();
}

以這種方式繞過 fun1() 和 fun2(),如下面的完整程式碼中所示 −

示例

 線上演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button type="submit" onclick="callTwoOtherFunctions()"> Call
</button>
<script>
   function callTwoOtherFunctions(){
      fun1();
      fun2();
   }
   function fun1(){
      console.log("Function1()")
   }
   function fun2(){
      console.log("Function2()")
   }
</script>
</body>
</html>

要執行以上程式,儲存檔名“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用即時伺服器開啟”選項。

輸出

這將生成以下輸出 −

當你單擊“呼叫 (Call)”按鈕時,你會得到以下輸出。快照如下所示 −

更新於:03-Sep-2020

473 次瀏覽

開啟 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.