客户端的JAVASCRIPT实例之一个简单的JAVASCRIPT程序
<html> <head><title>Example</title></head> <body> <h2>Table of Example</h2> <script> var fact=1; for(i=1;i<10;i++) { fact=fact*i; document.write(i+"!="+fact+"<br>"); } </script> </body> </html>
输出:
Table of Example
1!=12!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
一个定义了JAVASCRIPT事件句柄的HTML按钮
<button onclick="alert('You clicked the button');"> Click here </button>
用JAVASCRIPT编写的借贷支付金额计算器
<html> <head> <title>JavaScript Loan Calculator</title> <style> /* This is a CSS style sheet: it adds style to the program output */ .result { font-weight: bold; } /* For elements with class="result" */ #payment { text-decoration: underline; } /* For element with id="payment" */ </style> </head> <body> <form name="loandata"> <table> <tr><td><b>Enter Loan Information:</b></td></tr> <tr> <td>1) Amount of the loan (any currency):</td> <td><input type="text" name="principal" onchange="calculate();"></td> </tr> <tr> <td>2) Annual percentage rate of interest:</td> <td><input type="text" name="interest" onchange="calculate();"></td> </tr> <tr> <td>3) Repayment period in years:</td> <td><input type="text" name="years" onchange="calculate();"></td> </tr> <tr> <td></td> <td> <input type="button" value="Compute" onclick="calculate();"> </td> </tr> <tr> <td> <b> Payment Information: </b></td></tr> <tr> <td>4) Your monthly payment:</td> <td>{1}lt;span class="result" id="payment"></span></td> </tr> <tr> <td>5) Your total payment:</td> <td>{1}lt;span class="result" id="total"></span></td> </tr> <tr> <td>6) Your total interest:</td> <td>{1}lt;span class="result" id="totalinterest"></span></td> </tr> </table> </form> <script language="JavaScript"> function calculate() { var principal=document.loandata.principal.value; var interest=document.loandata.interest.value/100/12; var payments=document.loandata.years.value*12; var x=Math.pow(1+interest,payments); var monthly=(principal*x*interest)/(x-1); var payment=document.getElementById("payment"); var total=document.getElementById("total"); var totalinterest=document.getElementById("totalinterest");; if(isFinite(monthly)) { payment.innerHTML=monthly.toFixed(2); total.innerHTML=(monthly*payments).toFixed(2); totalinterest.innerHTML=((monthly*payments)-principal).toFixed(2); } else { payment.innerHTML = ""; total.innerHTML = "" totalinterest.innerHTML = ""; } } </script> </body> </html>
斐波那契数列
<script> document.write("<h2>Table of Fibonacci Numbers</h2>"); for(i=0,j=1,k=0,fib=0;i<50;i++,fib=j+k,j=k,k=fib) { document.write("Fibonacci(" + i + ") = "+ fib); document.write("<br>"); } </script>
在对话框中显示纯文本的斐波那契数列
<script> document.write("<h2>Table of Fibonacci Numbers</h2>"); for(i=0,j=1,k=0,fib=0;i<50;i++,fib=j+k,j=k,k=fib) { alert("Fibonacci(" + i + ") = "+ fib); document.write("<br>"); } </script>