JS函数 函数调用 函数定义好后,是不能自动执行的,需要调用它,直接在需要的位置写函数名。

函数调用

函数定义好后,是不能自动执行的,需要调用它,直接在需要的位置写函数名。

第一种情况:在<script>标签内调用。

  <script type="text/javascript">
    function add2()
    {
         sum = 1 + 1;
         alert(sum);
    }
  add2();//调用函数,直接写函数名。
</SCRIPT>

第二种情况:在HTML文件中调用,如通过点击按钮后调用定义好的函数。

<html>
<head>
<script type="text/javascript">
   function add2()
   {
         sum = 5 + 6;
         alert(sum);
   }
</script>
</head>
<body>
<form>
<input type="button" value="click it" onclick="add2()">  //按钮,onclick点击事件,直接写函数名
</form>
</body>
</html>

注意:鼠标事件会在后面讲解。

任务

补充右边编辑器第15行,实现如下功能:

网页中有一按钮(名字"点点我"),当点击按钮后调用函数tcon(),弹出对话框"恭喜你学会函数调用了!"。


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>函数调用</title>
<script type="text/javascript">
function tcon()
  {
	alert("恭喜你学会函数调用了!");
  }
</script>
</head>
<body>
<form>
<input type="button"  value="点点我" onclick="tcon()">  
</form>
</body>
</html>



原文地址:https://www.cnblogs.com/yongbin668/p/5592782.html