Transcript 投影片 1

JavaScript
鄧姚文
http://www.ywdeng.idv.tw
JavaScript 簡介



Client-Side JavaScript (CSJS)
Mozilla Foundation implementation of the
ECMAScript standatd
JavaScript is NOT Java


Java 和 JavaScript 在語法方面相似,但是在變
數宣告、資料型別與物件導向方面有許多差異
Netscape 起初命名為 LiveScript,因為和 Sun
Microsystems 合作,改名為 JavaScript
2
JavaScript 簡介

JavaScript的功能


控制瀏覽器的動作與內容
JavaScript的優點




直譯式語言, 簡單易懂
安全:無法經由網路從他處傳輸資料, 也無法讀
取使用者硬碟中的資料
直接反應使用者的要求, 無須透過伺服器
瀏覽器解譯程式, 可跨作業平台執行
3
環境設定

Firefox:瀏覽器


官方網站: http://www.mozilla.com/
Firebug:JavaScript 除錯附加元件


以 Firefox 開啟這個 下載點
或到 Firefox 附加元件網站
https://addons.mozilla.org/ 搜尋 firebug
練習:Hello JavaScript

以 document.write 方法輸出字串 “Hello
JavaScript”



document 代表這個HTML文件
write() 輸出字串的副程式
JavaScript 程式碼必須以
<script type="text/javascript">
</script>
夾住前後
5
語言特性



Dynamically Typed 動態資料型別
Interpreted 直譯,逐行編譯執行
Functions as First-Class Objects 函式即物件
6
語言特性

Dynamically Typed 動態型別



Data types are NOT declared
Data types are NOT known until execution time
Data type is associated to the value of the
variable rather than the variable itself
var x = 5;// set x to 5 (number)
x = "Hello!"; // set x to "Hello!" (String)
7
語言特性

Interpreted 直譯式語言


The code is stored as text and interpreted into
machine instructions and stored in memory as
the program runs.
Line by line 逐行譯、逐行執行
8
語法概述

利用 “.” 來連接 “物件”與





其所擁有的屬性(Property)
能夠改變其狀態的方法(Method)
與其有下層關係的物件 (Object)
利用物件名稱.屬性名稱 = 屬性值, 可以改變物件
的屬性值, 亦即改變物件的狀態
利用物件名稱.方法名稱(), 即可呼叫某物件的方法,
改變物件的狀態
9
語法概述

變數宣告方式



一般變數宣告:
[var] 變數名稱[=變數值];
陣列變數宣告:
[var] 變數名稱 = new Array([數量|陣列值]);
物件變數宣告: (宣告物件一定要var)
var 變數名稱 = new 物件名稱;
10
語法概述

函數宣告



Functions as First-Class Objects


函數宣告方式:
function 函數名稱([參數1,參數2])
函數若有回傳值不須預先宣告型態, 只須利用
return(var)在函數結束前將值回傳即可
Function is a type of built-in object
Functions are unique only by name, not by
name plus arguments
11
語言特性
Functions as First-Class Objects
var newMethod = new Function("alert('new method');");
newMethod();
// alerts "new method"
function newMethod2() {
alert('new method');
}
newMethod2();
// alerts "new method"
12
語法概述





JavaScript 大小寫字母意思不同
除非是在字串中, 否則空白或TAB字元都會被忽
略; 而分號則表示一行程式結束, 用法同C語言
可以‘單引號’或“雙引號”夾住字串內容
特殊字元的表達方式與C語言相同, 例如換行字
元為 ‘\n’
/* 多行註解 */
// 單行註解
13
在網頁中撰寫使用JavaScript

HTML文件中三種呼叫使用樣式的方法




第一種方法是直接撰寫在HTML標籤中, 並透過事件
處理器來執行JavaScript。例如<font size="+4"
onMouseover='color="#ff00ff"'>test1</font>
第二種方法是將JavaScript程式碼放置於<script>
</script>標籤中。<script>標籤可放置於HTML文件
的任何位置, 執行順序則依照其所在的位置先後被
執行。
第三種方法是將JavaScript程式碼寫在.js檔案中, 再
利用<script>的src屬性指定.js檔案的位置, 將其匯
入HTML文件中
後兩種方式的程式碼中若要操作HTML中的特定標
籤, 則需給定該標籤的id屬性值(命名)
14
JavaScript事件觸發方式

利用HTML標籤(元件)中的事件處理器。
<font size="+4" onclick= 'color="#ff00ff"'> test1</font>
<font size="+4" onclick= “change();”> test1</font>

在JS程式碼中捕捉元件事件
<script LANGUAGE="javascript">
document.onclick = change;
function change() {
document.getElementById("a").color = "#ff00ff";
}
</script>
<font id="a" size="+4"> test1</font>
15
基本資料型別

Primitive Data Types




boolean 真/假
number 數字(有小數點)
string 文字
Special values


undefined 未定義
null 虛空
16
基本資料型別

booleans 布林,真/假、是/否

Possible values




true
false
1 相當於 true
0 相當於 false
var x
var y
var z
alert
= false;
= true;
= 1;
(y === z);
// alerts 'true'
17
基本資料型別

Numbers 數字



64位元值
Similar to double in Java
進行整數運算時:

先轉成 32-bit 整數(無條件捨去),運算完畢再轉
回 64-bit number
var x = 6;
// x: 64-bit
var y = x << 2;// x: 32-bit, y: 64-bit
18
練習:印出從一到十的數字

以 document.write 輸出從 1 到 10 的數字

迴圈:


while (條件) { … }
for (初值; 條件; 改變) { … }
19
練習:印出從一加到十的結果

以 document.write 輸出從 1 加到 10 的結果

條件判斷:




if (條件) { … }
if (條件) { … } else { … }
if ((條件1) && (條件2)) { … }
if ((條件1) || (條件2)) { … }
20
Special Number Values
21
基本資料型別

Strings 字串


A string is a sequence of zero or more Unicode
values used to represent text.
Strings are immutable



Modification produces a new string
JavaScript 只有字串,沒有字元型別
單引號與雙引號皆可
22
Special Characters 跳脫字元
23
練習:九九乘法表

以 document.write 輸出九九乘法表


作法一:以<pre>標籤配合 \t 定位
作法二:以<table>排版


試試看:以 bgcolor 做出間隔列顏色不同的變化
試試看:以 CSS 的 tr:hover 做出隨著滑鼠移動的螢
光棒
24
物件 Objects

除了 boolean, number, string 這些 Primitive
Data Type 之外,其餘的一切都是物件



Function
Date
Document Object Model (DOM) elements
var myCar = new Object(); // the built-in Object type
var myCar2 = {}; // the object literal
25
物件 Objects

Object properties are stored using an
associative array
26
Using a for … in loop
27
Object Functions
28
Object Literal Notation
29
Expando Properties
myCar.print = null;
delete myCar.print;
30
Primitive Data Type Wrapper Objects
封裝物件



Boolean, Number, String
Primitive data types just store data and don’t
have any methods or properties
JavaScript silently converts the primitive
data types to and from the wrapper objects
so that we can use methods without having
to cast to another object first
31
instanceof

instanceof determines whether an object
derives from a particular type
The constructor Property



建構,在 new 時呼叫
The constructor property references the
function that created an object
can be used to determine an object’s type
相等 & 不相等

Equality 相等

Equal ==


Not equal !=


資料值不相等
Strict equal ===



資料值相等
compare both the value and type of the operands
資料值和資料型別都相等
Strict not equal !==
Variables and Function Arguments

區域變數只存在於 function(){} 內



Only the global object (the window object in
browsers) and functions are variable scope
boundaries
Other blocks, such as if-then-else statements
and while loops, don’t provide a variable scope
boundary.
Variables declared inside a block other than the
function block will be accessible outside that
block
Function-Level Variable Scope
Globally Scoped Variables

The global window is the root of the DOM
and is accessed through the window keyword
練習

乘法計算


輸入兩數字 x 和 y,計算並印出 z = x * y
技巧:


<input type="text" id="x" /> 提供文字輸入
<input type="button" onclick="doIt()" value="計
算" />

產生按鈕,驅動計算
document.getElementById("x").value 存取文字方
塊內的值

m = parseInt(x)
將字串轉換成數字(非必要)
38
Undeclared Variables

不宣告就使用的變數,自動宣告成全域變
數
Null(空) and undefined(未定義)


null is a reserved word that means no value
and is used to point a variable to no data so
that memory can be reused
undefined is the default value of a newly
declared variable

undefined is a primitive value and a type
Comparing null and the undefined Value
『型別』不是『值』
alert(typeof(y)==typeof(z)); // alerts true
alert(y==z);
// can not execute
alert(y===z);
// can not execute
Comparing null to Itself

Comparing a null valued variable and an
undefined valued variable will evaluate to
true when using the nonstrict comparison
and evaluate to false when using the strict
comparison
值是 null,型別不是 null
Comparing Using the undefined Type

use undefined as a type
typeof(x) 應該是 undefined
alert(typeof(x) == undefined);
// alerts false
typeof 取得型別

typeof returns a string based on the data
type of its operand
typeof Evaluations
Function Arguments 參數


Method arguments are always supplied to
the function in a special local arguments
variable
Local variable is accessible once inside the
function through the arguments keyword
Implicit Arguments
Explicit Arguments
Undefined Arguments
Dynamic Arguments
callee 被呼叫者


The callee property available on a function’s
local arguments variable accesses the
function being executed
using arguments.callee to access the
sayHello method
Recursive Anonymous Methods with
arguments.callee
練習


印出 N 階乘,包括計算過程與結果
例如:


5! = 1 * 2 * 3 * 4 * 5 = 120
技巧:


以 <div id="z" /> 作為輸出位置
以 document.getElementById("z").innerHTML 存取
div 內的 HTML 字串
53
this


this in JavaScript points to the current owner
of the executing method
can point to



the global window object if the executing method
is procedural,
a DOM element if the executing method is
handling a DOM event, or
an object if the executing method is contained
within the object’s definition
The Different Uses of this
Error Handling

Try-Catch-Finally Mechanism

Code wrapped in a try block that causes an error
to be thrown transfers control to the catch block,
which receives as a parameter an instance of
the built-in Error type describing the error that
occurred
Standard Error Properties

The catch block accepts a single parameter,
e, which is an instance of the Error type. The
Error type has two standard properties
Nonstandard Error Properties
Throwing an Error
Using the finally Block

the finally block always executes after either
the try block or the catch block execution is
complete
Using the finally Block
Unhandled Exceptions

The other error handling mechanism is the
global error event attached to the window,
which can be used as a catchall for
unhandled errors
The Error Event Handler

The signature for the error handler function
takes three parameters: the error message,
the URL of the page where the error
occurred, and the line number of where the
error occurred
Globally Handling an Error
Delayed Code Execution Using Timeouts
and Intervals


Timeouts execute only after the delay expires
Intervals execute when the time delay
expires and then reset themselves so that
they will continually execute after the delay
expires
Timeouts



Creating a timeout is done through the
window.setTimeout method
the amount of the delay is in milliseconds
Use window.clearTimeout method to unregister timeout
Explicit Anonymous Function
Problems with Functions and Variables
Inducing Scope for Our Predefined
Function
Intervals


Intervals are identical to timeouts except
that the function or string expression is
continuously evaluated at the specified
interval until the interval is canceled, instead
of executing only one time when the delay
expires
using a window.setInterval method
Using an Interval
Clearing an Interval
練習:電子鐘




在網頁上顯示目前日期時間
每半秒鐘更新一次
<body onload="showClock()">
d = document.getElementById("clock")


<div id="clock" align="right"></div>
d. innerHTML = …
練習:動態顯示


列出蔬菜水果清單
當滑鼠經過清單中某一蔬果時,在下方顯
示蔬果的圖與名稱
練習:簡易計算機

設計一個可以進行兩個數字四則運算的計
算機
JavaScript中的物件

始祖物件window 所有物件皆繼承它

核心物件: 內建物件, 不受JS使用環境的差異影
響使用方式


環境物件: 用以存取瀏覽器資訊, 使用方式可能
會因瀏覽器不同而有不同


Array, Boolean, Date, Error, Function, Global, Math,
Number, Object, RegExp, String
location, navigator, history, screen
文件物件: 代表Html文件, 可透過document提供
的方法存取其中的元件
76
JavaScript中的物件
屬性
說明
屬性
說明
length
視窗框架數目
closed
name
視窗的名稱
defaultStatus 視窗狀態列預設文字
status
視窗的狀態列文字
screenLeft
視窗左上角在螢幕X軸位置(For IE)
opener
開啟視窗的呼叫者參照 screenTop
視窗左上角在螢幕Y軸位置(For IE)
parent
父框架參照
screenX
視窗左上角在螢幕X軸位置(For NS)
top
頂層框架參照
screenY
視窗左上角在螢幕Y軸位置(For NS)
window 同self
pageXOffset
網頁在視窗顯示區X軸位置(For NS)
self
pageYOffset
網頁在視窗顯示區Y軸位置(For NS)
window物件本身
視窗是否已經關閉(True/False)
77
JavaScript中的物件 (續)
方法
說明
方法
說明
moveBy(x, y)
移動視窗x, y個像素
moveTo(x, y)
resizeBy(x, y)
調整視窗增減x, y個像素
resizeTo(x, y) 調整視窗成x, y大小
scrollBy(x, y)
調整捲軸增減x, y個像素
scrollTo(x, y)
prompt(msg,
[input])
開啟對話視窗顯示msg,
input為預設值
confirm(msg) 開啟確認視窗顯示msg 並
回傳True/False
alert(msg)
開啟警告視窗顯示msg
close()
關閉視窗
setTimeOut
(exp, time)
啟動計時器並於time指定
的時間(千分之一秒)到達
後執行exp的運算式
setInterval
(exp, time)
啟動計時器並以time指定
的時間(千分之一秒)週期
性執行exp的運算式
clearTimeOut()
停止setTimeOut的計時器
clearInterval() 停止setInterval的計時器
open(url, name,
features)
開啟url文件,命名為 name, print()
外觀設定為feature的視窗
78
移視窗至(x, y)座標點
調整捲軸使顯示區左上角
在網頁x, y的位置
列印網頁
JavaScript中的物件 (續)

開啟新視窗時(使用window.open()方法)可設
定的相關外觀參數:
參數
說明
參數
copyhistory 是否複製瀏覽記錄(0 or 1) toolbar
說明
是否顯示工具列
directories
是否顯示導覽列
scrollbars 是否顯示捲軸
fullscreen
是否全螢幕顯示
resizable
是否可以改變視窗大小
location
是否顯示網址列
height
視窗高度
menubar
是否顯示功能表列
width
視窗寬度
status
是否顯示狀態列
79
JavaScript中的物件 (續)

屬性
location物件: 存取或操縱目前開啟網頁的網
址資訊(URL)
說明
屬性
hash
URL中#號後面的資料
host
URL中主機名稱與連接阜名稱 hostname
port
URL中連接阜名稱
protocol
URL中通訊協定名稱
href
URL, 可變更此屬性將瀏覽器
導向其他網頁
search
URL中?號後面的資料
方法
pathname
說明
說明
reload 重新整理網頁
方法
Replace(url)
80
URL中的檔案名稱與路徑
URL中的主機名稱
說明
將瀏覽器導向參數url指
定的網址
JavaScript中的物件 (續)

navigator物件: 存取瀏覽器與系統資訊 (資訊
皆為唯讀)
屬性
說明
屬性
說明
appCodeName
瀏覽器的程式碼名稱
cpuClass
CPU類型
appName
瀏覽器名稱
platform
作業系統平台
appMinorVersion 瀏覽器的次版本
plugins
外掛程式
systemLanguage
系統預設的語系
userProfile 使用者
userLanguage
使用者設定的語系
userAgent HTTP通訊協定資訊
appVersion
瀏覽器版本與作業系統
onLine
名稱
81
目前系統是否在線上
JavaScript中的物件 (續)


history物件: 存取瀏覽器的歷史紀錄
window.history.back(); 可使網頁回到上一頁
屬性
length
說明
歷史紀錄數目
方法
back()
說明
回到上一頁
forward() 回到下一頁
go(num)
回到上幾頁(num < 0)或移到下幾頁(num > 0)
82
JavaScript中的物件 (續)


screen物件: 取得系統螢幕設定資訊
var SH = window.screen.height; 可取得螢幕
高度的解析度並設定給SH變數
屬性
說明
availHeight
螢幕視野的高度 (像素)
availWidth
螢幕視野的寬度 (像素)
colorDepth
螢幕的色彩深度 (表達像素的位元數)
height
螢幕高度的解析度 (像素)
width
螢幕寬度的解析度 (像素)
83
JavaScript中的物件 (續)

document物件: 存取網頁上所有元件, 包含
<html>標籤之間的表單,圖片,表格超,連結,
框架
屬性
說明
屬性
說明
charset 瀏覽器的字元集(For IE) characterSet
瀏覽器的字元集(For NS)
cookie
height
Html文件的高度(For NS)
domain 伺服器端的網域名稱
width
Html文件的寬度(For NS)
referer
連結至Html的URL
lastModified
Html最近修改時間
url
Html文件的URL
Title
瀏覽器的標題列文字
瀏覽器端的Cookie
84
JavaScript中的物件 (續)
方法
說明
方法
說明
close()
關閉 Html文件
getElementById(i)
取得文件中ID屬性
值等於變數i的元件
open(type)
根據type指定的
MINE類型在同視窗
開啟新文件(非開啟
檔案)
getElementByName(n)
取得文件中Name屬
性值等於變數n的元
件
writeln(data) 將data字串加上換行
符號後輸出至瀏覽器
write(data)
getElementByTagName(t) 取得文件中標籤名稱
等於變數t的元件
將data字串輸出至瀏
覽器
85
JavaScript中的物件 (續)
集合
說明
集合
說明
all
網頁上所有物件
anchors
所有有name屬性的<A>標籤
forms
網頁上所有表單
links
所有有href屬性的<A>標籤
images
網頁上所有圖片
styleSheets
網頁上所有樣式表
applets, embeds, plugins
所有Java Applets, 嵌入元件或外掛程式
86
JavaScript中的物件 (續)
除集合外, document物件有一子物件body,
其相關屬性如下:


document.body.bgColor = “Blue”; 可將整個網頁
的背景顏色設定為藍色
屬性
說明
link
對應<body>標籤的LINK屬性, 表示尚未瀏覽過的超連結文字色彩
alink
對應<body>標籤的ALINK屬性, 表示超連結文字被選取時的色彩
vlink
對應<body>標籤的VLINK屬性, 表示已瀏覽過的超連結文字色彩
background 對應<body>標籤的BACKGROUND屬性, 表示網頁背景圖片
bgColor
對應<body>標籤的BGCOLOR屬性, 表示網頁背景色彩
text
對應<body>標籤的TEXT屬性, 表示網頁中文字色彩
87
JavaScript中的事件
事件
說明
事件
說明
onLoad
瀏覽器載入文件或框架時
onKeyPress
在元件上按下後放開鍵盤時
onUnload
關閉瀏覽器時
onKeyDown 在元件上按下鍵盤時
onClick
滑鼠在元件上按一下時
onKeyUp
在元件上放開鍵盤時
onDbclick
滑鼠在元件上連按兩下時
onSubmit
傳送表單時
onMouseDown
滑鼠在元件上按下按鍵時
OnReset
清除表單內容時
onMouseUp
滑鼠在元件上放開按鍵時
onSelect
表單欄位內容被選取時
onMouseOver
滑鼠滑過元件時
onChange
表單欄位內容被變更時
onMouseMove
滑鼠在元件上移動時
onMove
移動瀏覽器視窗時
onMouseOut
滑鼠移開元件時
onResize
變更瀏覽器視窗大小時
onFocus
焦點移動到元件時
onAbort
取消載入網頁或圖片時
onBlur
焦點移開元件時
onError
網頁發生錯誤時
88