如何使用"onclick"JavaScript 运行两个或更多函数?

javascriptweb developmentobject oriented programming更新于 2025/11/6 4:28:17

我们先设置一个按钮 −

<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 编辑器中选择选项"使用 Live Server 打开"。

输出

将产生以下输出 −

单击"调用"按钮后,将获得以下输出。快照如下 −


相关文章


有用资源