1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>JavaScript-什么是函数</title>
6 <script type="text/javascript">
7 function 函数名(){ 8 函数代码
9 }//函数定义语法
10 </script>
11 </head>
12 <body>
13 </body>
14 </html>
为了避免代码的重复书写的麻烦,我们把完成某一个特定功能的一组语句称之为函数,通过函数的调用实现了代码的复用性与可阅读性;
- function定义函数的关键字
- "函数名"你为函数取的名字
- "函数代码"替换为完成特定功能的代码
- 函数定义好后,是不能自动执行的,所以需调用它,只需直接在需要的位置写函数就ok了
专门建立的学习Q-q-u-n: 784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习技巧
(从零基础开始到前端项目实战教程,学习工具,全栈开发学习路线以及规划)
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>JavaScript-什么是函数</title>
6 <script type="text/javascript">
7 /*
8 function 函数名(){
9 函数代码
10 }//函数定义语法
11 */
12 function add2(){
13 var sum=3+2;
14 alert(sum);
15 // document.write(sum);
16 }
17 add2();//调用函数直接写函数名称
18 </script>
19 </head>
20 <body>
21 <input type="button" name="" id="" value="点击" onclick="add2()"/>
22 <!-- 单击按钮,调用函数,onclick为点击事件 -->
23 </body>
24 </html>
相关拓展:网页中有一按钮(名字"点击我"),当点击按钮后调用函数contxt(),弹出对话框"哈哈,调用函数了!"。
1 <!DOCTYPE HTML>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>函数调用</title>
6 <script type="text/javascript">
7 contxt() //定义函数
8 {
9 alert("哈哈,调用函数了!"); 10 } 11 </script>
12 </head>
13 <body>
14 <form>
15 <input type="button" value="点击我" onclick=" " />
16 </form>
17 </body>
18 </html>