JavaScript自訂function函數
能夠重複使用的程式碼,提升程式的模組化
<script>
function func_name(傳入參數){
return 變數名稱
}
</script>
自訂函數可呼叫其他自訂函數,但不宜太多層過於複雜,才能顧及後續的維護及修改
引用外部自訂函數
filename.js
unction futurevalue(){
var pv = parseInt(document.getElementById(“amount”).value);
var i = parseFloat(document.getElementById(“rate”).value);
var n = parseInt(document.getElementById(“period”).value);
fv=pv*(Math.pow(1+i,n));
document.write(“本利合 = “ + fv + “</br>”);
}
E_5_3.html
<!DOCTYPE html>
<html>
<head>
<script type=”text/javascript” src=”myjsfile.js”></script> #宣告type
</head>
<body>
<h3>引用外部自訂函數</h3>
<form action=”/result/” method=”get”>
<fieldset><legend>計算本利和:</legend>
存款金額:<br>
<input type=”text” id=”amount” name=”amount” value=”100"> <br>
年利率:<br>
<input type=”text” id=”rate” name=”rate” value=”0.03"><br>
期數:<br>
<input type=”text” id=”period” name=”period” value=”5"><br>
</fieldset>
<br><button type=”button” id=”btn” onclick=”futurevalue()”>>送出!</button>
</form>
<script src=”myjsfile.js”></script>
</body>
</html>
使用GetVal()取id標籤的值傳給自訂函數
filename.js
function futurevalue(pv,i,n){ #宣告參數
var fv=pv*(Math.pow(1+i,n));
document.write(“本利合 = “ + fv + “</br>”);
}
E_5_3.html
<!DOCTYPE html>
<html>
<head>
<script type=”text/javascript” src=”myjsfile.js”></script>
</head>
<body>
<h3>引用外部自訂函數</h3>
<form action=”/result/” method=”get”>
<fieldset><legend>計算本利和:</legend>
存款金額:<br>
<input type=”text” id=”amount” name=”amount” value=”100"> <br>
年利率:<br>
<input type=”text” id=”rate” name=”rate” value=”0.03"><br>
期數:<br>
<input type=”text” id=”period” name=”period” value=”5"><br>
</fieldset>
<br><button type=”button” id=”btn” onclick=”futurevalue(GetVal(‘amount’),GetVal(‘rate’),GetVal(‘peroid’))”>> 送出!</button> #GetVal()
</form>
<script src=”myjsfile.js”></script>
</body>
</html>