在 JavaScript 中從 index.html 頁面呼叫非同步程式碼?


您需要將 async 和 await 與 body onLoad 屬性一起使用 以下為程式碼 −

index.html

示例

 線上演示

<!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>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.
css" 
crossorigin="anonymous">
</head>
<body onLoad="callFunction()">
<script>
   async function callFunction(){
      await testFunction();
   }
   function testFunction(){
      console.log("Hi...");
   }
</script>
</body>
</html>

要執行以上程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在 VS 程式碼編輯器中選擇“使用 Live Server 開啟”選項。

輸出

這會產生以下輸出 −


更新日期:07-Sep-2020

207 次瀏覽

啟動你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.