JavaScript 回调

javascriptweb developmentfront end technology更新于 2024/7/13 18:46:00

在 JavaScript 中,由于函数是对象,因此我们可以将它们作为参数传递给另一个函数。然后可以在另一个函数中调用这些函数,传递的函数称为回调函数。

以下是 JavaScript 回调的代码 −

示例

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>JavaScript Boolean constructor Property</h1>
<p class="sample"></p>
<button class="btn">点击此处</button>
<h3>
Click on the above button to call the add function which calls back
another function
</h3>
<script>
   function add(a, b, callback) {
      callback(a + b);
   }
   function multiplyResultByTwo(res) {
      document.querySelector(".sample").innerHTML = res * 2;
   }
   document.querySelector(".btn").addEventListener("click", () => {
      add(4, 5, multiplyResultByTwo);
   });
</script>
</body>
</html>

输出

点击“CLICK HERE”按钮 −


相关文章