作者:Thau! |
该HTML页含有一个叫做announceTime的函数。从一个链接阀用 annoumnceTime: |
<a href="#" onClick="announceTime();">time!</a> |
就象这样: 下行看起来就象第二课: |
<a href="#" onClick="alert('Hello!');">Hello!</a> |
这称为从一个链接调用警告对话框。函数就象一种方法, 让我们回到函数本身。如果你看看源码,你将看到函数位 |
<html> <head> <title>Function with No Parameters</title> <script langauge="JavaScript"> <!-- hide me function announceTime() { //get the date, the hour, minutes, and seconds var the_date = new Date(); var the_hour = the_date.getHours(); var the_minute = the_date.getMinutes(); var the_second = the_date.getSeconds(); //put together the string and alert with it var the_time = the_hour + ":" + the_minute + ":" + the_second; alert("The time is now: " + the_time); } // show me --> </script> </head> <body> ... </body> </html> |
好,让我们逐行复习这个函数。首先,所有函数来自于该种格式: |
function functionName(parameter list) { statements ... } |
函数的命名规则于变量差不多。第一个字符必须是字母或 一标准符号。其余字符可为数字或一横线。但必须保证函 数不于已定义的变量同名。否则将出现很糟糕的结果。我 是用内部大写的方式命名函数以保证它们不与字符碰巧重 名。 函数名后是一组参数。本例是无参数的函数,下一例中我 参数后是函数的主体。这是一组当函数调用后是想运行的 第一行: |
var the_date = new Date(); |
取得一个新的日期对象。就象你在用数组时取得一个新的 这些方法从日期对象上取得了合适的数字。 |
var the_hour = the_date.getHours(); var the_minute = the_date.getMinutes(); var the_second = the_date.getSeconds(); |
你可能疑惑:我怎样能假定日期对象知道何种方式?甚或 对象,但不一定能彻底的使你清楚。 函数的其他部分就很清楚了。它以这种方式调用 现在如果你也玩透了时间链接,你可能注意到了有些什么 这是getSecond()将返回值为“4”。那么当你合成为时间 时,你看到的就是the_minute+“:”+the_second得到14:4 而非是我们想要的。解决它是个容易的事,需要个新的函 数来修补分、秒合成值。 请看参数及返回值 |
第1页: 第四课介绍 第2页: 循环介绍 第3页: 循环的密码 第4页: 再谈WHILE循环 第5页: For 循环 第6页: 嵌套循环 第7页: 循环练习 第8页: 数组 第9页: 数组和循环 第10页:文件目标模块中的数组 第11页: 函数 第12页: 无参数函数 第13页: 参数及返回值 第14页: 多于一个参数的函数
|