如何在 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