JS:3.1,函數(function)-定義 返回頂部 |
1,定義函數語法
通過定義函數名稱,參數和代碼語句來創建函數。
function 函數名([參數1,][參數2,][...])
{
語句:
}
備注:
[]內的內容可以不寫。
參數是函數中使用的變量,變量的值是別調用函數按值傳值的。通過將函數放置在文檔的頭部分(head),函數中的代碼將在函數被調用之前加載。
2,怎樣調用函數
一個函數在沒被調用之前將不會執行。
(1)調用包含參數的函數。
函數名([參數1,][參數2,][...])
(2)調用不包含參數的函數。
函數名()
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script language="javascript">
function total(a,b)
{
result=a+b;
return result;
}
</script>
</head>
<body>
<h1>1,返回語句</h1>
<script language="javascript">
var a=3;
var b=1;
var sum=total(a,b);
document.write(sum);
</script>
</body>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script language="javascript">
function fun()
{
alert("Hello!");
}
</script>
</head>
<body>
<pre>
<h1>2,調用一個函數</h1>
<input type="button" onclick="fun()" value="調用函數" />
<a href="javascript:fun()">調用函數</a><br />
<p>
通過按下按鈕,一個函數將被調用。這個函數將彈出一個消息框
</p>
</pre>
</body>
</html>
JS:3.4,函數-調用一個函數(帶參數) 返回頂部 |
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script language="javascript">
function fun(word)
{
alert("Hello "+word+"!");
}
</script>
</head>
<body>
<pre>
<h1>2,調用一個函數(帶參數)</h1>
<input type="button" onclick="fun('小姐')" value="調用函數" />
<p>
通過按下按鈕,一個函數將被調用。這個函數將彈出一個消息框。
</p>
</pre>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script language="javascript">
function fun()
{
return ("你好,今天天氣很不錯!");
}
</script>
</head>
<body>
<h1>4,返回值的函數</h1>
<script language="javascript">
document.write(fun());
</script>
<p>
在body中的腳本調用函數。
</p>
<p>
這個函數返回一段文本。
</p>
</body>
</html>
3.6.1, a1.js
function fun()
{
alert("你好,今天天氣很不錯!");
}
3.6.2,
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script src="a1.js" language="javascript"></script>
</head>
<body>
<h1>
5,調用外部的js文件
</h1>
<input type="button" onclick="fun()" value="調用函數" />
</body>
</html>