SlideShare ist ein Scribd-Unternehmen logo
1 von 53
JavaScript 快速上手

   上官林傑 (ericsk)
課程大綱

JavaScript 簡介
基本語法
用 JavaScript 控制網頁元素 (DOM)
事件處理 (Event)
Ajax
JavaScript Framework 簡介
範例討論
前言

因為課程設定為基礎課程,所以 JavaScript 的語言部份不會深入
研究。目的在能了解基本 JavaScript 語法的撰寫,以及與 HTML
的結合應用。
JavaScript 簡介

 一種程式語言,與 Java 無關 ,而且並不是簡單 的語言!
   直譯式程式語言,由瀏覽器的 JS 引擎執行
     瀏覽器支援性問題
   動態(弱)資料型態
   可以動態執行程式碼 -- eval()
   單一執行緒
     運用 timer 作非同步多工
 目前最多的應用在網頁設計上。
   script 在瀏覽器上執行,所以 user 會看到全部的程式碼
     千萬不要放重要資訊在 JS 的程式碼裡
   上線環境下,js 檔案(或 CSS檔案)最好「壓縮」過
     減少傳輸量
JavaScript 的使用

 你可以:
   改變網頁元素的內容、樣式
   處理使用者在網頁上的動作(點擊、按鍵等)
   與網站的 Server 溝通(AJAX)
   ...
 你不行:
   儲存或讀取使用者電腦裡的資料(檔案、記憶體等)
   與其它網站建立連線(SOP)
   編修網頁上的圖片(resize, rotate)
在網頁中使用 JavaScript

 用 <script> 標籤:
 <script type=quot;text/javascriptquot;>
     window.alert('hello, world!');
 </script>

 寫在 *.js 檔案裡再引入:
 <script type=quot;text/javascriptquot; src=quot;hello.jsquot;></script>
JavaScript 的偵錯(debug)方式

 用 window.alert() 印出變數的值,或是用來判斷程式是
 否執行到此。
   好處:任何瀏覽器都支援
   缺點:如果在迴圈中 debug,彈出視窗按不完...
 利用 Firefox 的 firebug 套件
   好處:功能很強
   缺點:只能在 firefox 上使用。
 利用 YUI Logger
   好處:不限瀏覽器
   缺點:擋在畫面上比較麻煩
基本語法 -- 注意事項

 程式碼的字母大小寫有別 (case-sensitive)
                    WHILE(a != 0) {
 while (a != 0) {
                       ....
    ....
                       a = a - 1;
    a = a - 1;
                    }
 }
 可以不加 ; 在結尾 -- 一行一個敘述句

                  a=2
 a = 2; b = 3;
 註解可以用 /* ... */ 或是 = 3
                  b //
變數 (Variable)

 用 var 關鍵字宣告,不過也可以省略
   重覆宣告OK,會採用最新的
   由英文字母、數字及 _ 組成,但首字不可是數字
   (可以用 $)
   變數的有效範圍
 基本資料型態
   數值: 3, 20, 23.5
   字串: 'aaa', quot;bbbquot;
   布林: true, false
   空值、未定義: null, undefined
   NaN
變數基本運算

數字
  基本運算: +, -, *, /, %
  邏輯運算:==, &&, ||
字串的 + 運算
  quot;abcquot; + quot;abcquot; = quot;abcabcquot;
  quot;3quot; + 3 = quot;33quot;
     parseInt(quot;3quot;) + 3 = 6
布林 值
  0, null, undefined, false, quot;quot;, NaN 在邏輯判斷上
  都是 false
  非以上值全為 true
流程控制 - 判斷式 (if)

 使用 if, else if, else 關鍵字。
 用法:

 if (判斷式1) {
   ...
 } else if (判斷式2) {
   ...
 } else {
   ...
 }
 如果只有一行敘述,也可以省略 {}
流程控制 - 判斷式 (switch)

switch (變數) {
    case 值1:
        ....
                 如果沒有 break; 則流程會繼續
        break;   到下一個 case
    case 值2:
        ...
        break;
    ...
    default:
        ...
}
流程控制 - 迴圈 (do while/while)
  用來重覆執行某一段程式碼

  var n = 10, i = 10;
  while (i < n) {
      i = i + 1;
  }
  // 這裡 i == 10

  var n =   10, i = 10;
  do {
    i=i     +1
  } while   (i < n);
  // 這裡 i   == 11
流程控制 - 迴圈 (for)
       1    2   5    4
for (敘述句; 判斷式; 敘述句) {
   3 .....
}

上一頁的例子可以寫成相同的 for 迴圈:

var n = 10, i;
for (i = 0; i < n; i = i + 1) {
    ;
}
// 這裡 i == 10
自訂函數
為了結構化函式、重覆利用程式碼,             例:
可以自訂函數                       function plus2(x)
                             {
function 函式名稱(參數列...) {          return x + 2;
                             }
    ...
}
                             var a = 10;
                             b = plus2(a);
也可以寫成:
                             // b 這裡 值為 12
var 函式名稱 = function(參數列) {
  .....
}
匿名函數 (anonymous function)

當某些 API 需要傳入一個 function 作為參數時,如果只用一次也
可以直接傳入一個匿名函數。

/* 每 1 秒顯示一次訊息 */
var timerId = setInterval(function(){alert('hi');}, 1000);
/* 清除 timer */
clearInterval(timerId);

/* 1秒後顯示 */
setTimeout(funciton(){alert('!!');}, 1000);
進階資料型態: 陣列 (Array)

可以擺放連續資料的結構,再透過 index 的方式取得或設定資
料的內容。


生成陣列的方式:

                 var a = [123, quot;abcdquot;];
var a = [];
a[0] = 123;
                 var a = new Array(123, quot;abcdquot;);
a[1] = quot;abcdquot;;
使用陣列 (Array)
var a = new Array(123, 'abc', 456);
   取得陣列長度: a.length -> 3
   陣列相關函式:(以下例子各不相關,a 都是 (123, 'abc', 456)
      a.concat([100, 200]) -> [123, 'abc', 456, 100, 200]
      a.push(300) -> [123, 'abc', 456, 300]
      a.pop() -> [123, 'abc'] 並傳回 456
      a.shift() -> ['abc', 456]
      a.unshift(789) -> [789, 123, 'abc', 456]
      a.reverse() -> [456, 'abc', 123]
      a.sort() -> [123, 456, 'abc']
      a.slice(0, 2) -> [123, 'abc']
      a.join(',') -> quot;123,abc,456quot;
JSON - JavaScript Object Notation
JavaScript 中用來表示物件的資料結構。
var rect = {
  name: 'rectangle 1',
   width: 200,
   height: 100,
   area: function() {
     return this.width * this.height;
   }
};




r.area() -> 20000
r.width = 100;
r.area() -> 10000
用 JavaScript 操作網頁物件
取得文件元素

getElementById(id)

根據為標籤設的 id 來取得該元素,如:
var p = document.getElementById('panel');


<div id=quot;panelquot;></div>
<div id=quot;sidebarquot;></div>

p.innerHTML = '<h1>hello</h1>';


<div id=quot;panelquot;><h1>hello</h1></div>
<div id=quot;sidebarquot;></div>
取得文件元素 (續)
 getElementsByTagName(name)

 根據為標籤名稱 來取得該元素,如:
 var panels = document.getElementsByTagName('div');

 <div></div>
 <p>aaa</p>
 <div></div>

 for (var i in panels) {
     panels[i].innerHTML = 'hello';
 }

 <div>hello</div>
 <p>aaa</p>
 <div>hello</div>
文件物件模型 (DOM)

把結構化的文件(如:HTML, XML)的每一個標籤看作是一個物件,
並且有階層的概念。

<div>
                                    div
  <p id=quot;xquot;>Lorem ipsum dolor
sit</p>
  <ul>
    <li>abcd</li>               p         ul
    <li>1234</li>
  </ul>
</div>
                                               li
                                    li
文件物件模型 (DOM) (續)

var p = document.getElementById('x');

q = p.parentNode -> <div>
q.childNodes -> ['n ', <p>, 'n   ', <ul>, 'n']

p.getAttribute('id') -> 'x'
p.setAttribute('title', 'hello') ->
    <p id=quot;xquot; title=quot;helloquot;>
p.removeAttribute('id') -> <p title=quot;helloquot;>
改變文件元素的樣式
透過文件元素的 style 屬性來改變該元素的樣式,效果相當
於在標籤裡的 style=quot;quot; 一樣

var p = document.getElementById('x');
p.style.color = '#ff0000';
p.style.backgroundColor = '#00ffff';




                      CSS 屬性名稱如果有 - 的部份,就要把 - 去
                      掉,並且將下一字母大寫,如 text-align 就
                      要改成 textAlign
產生/移除文件元素

document.createElement(tagName )

用來產生新的元素

新增
var newDiv = document.createElement('div');
newDiv.id = 'new_d';
newDiv.innerHTML = 'hello';
document.body.appendChild(newDiv);

移除
var n = document.getElementById('new_d');
document.body.removeChild(n);
產生/移除文件元素 (續)

插入
var p = document.getElementById('x');
var newDiv = document.createElement('div');
newDiv.id = 'new_d';
newDiv.innerHTML = 'hello';
document.body.insertBefore(newDiv, p);
網頁事件
事件 (event)

瀏覽器會在網頁發生某些狀態改變、或是使用者的某些動作時產
生「事件」(event),透過 JavaScript 你可以處理這些事件發
生時,要做哪些事情。比方說:
  當使用者按下某個按鈕時
  當滑鼠游標移過某個元素時
  當整個網頁都載入時
  ...
元素標籤的 on Event 屬性

 指定某個元素的 onXXXX 屬性
 <input type=quot;buttonquot; value=quot;按我quot; onclick=quot;alert('我被按
 了!');quot; />

 這種方法雖然簡單快速,但難以處理複雜的狀況,程式碼也不
 好維護,同樣的動作無法重覆利用。
元素物件的 on Event 成員

 改寫該元素物件的 onXXXX 成員:

 <input type=quot;buttonquot; id=quot;btnquot; value=quot;按我quot; />

 <script type=quot;text/javascriptquot;>
 var btn = document.getElementById('btn');
 btn.onclick = function(evt) {
     alert('被按了..');
 };
 </script>
元素物件的 on Event 成員 (續)

 優點: 可以自己寫好事件處理的函式,然後再套用,可重覆利
 用也容易維護。更重要的是將 HTML/JavaScript 抽離。
 缺點: 如果同一個事件要做很多不同的事,就要自己處理要記
 得做哪些事,然後在 onEvent 中全部做完。(單一抽換也麻
 煩)

 function hand1(evt) { ... };
 function hand2(evt) { ... };
 x.onmouseover = function(evt) {
     hand1(evt);
     hand2(evt);
 };
註冊事件處理器

對物件註冊處理器 (利用 addEventListener 或
attachEvent)

<script type=quot;text/javascriptquot;>
function handleClick(evt) { alert('被按了'); };

var btn = document.getElementById('btn');
if (btn.attachEvent) { /* 為了 IE */
    btn.attachEvent('onclick', handleClick);
} else { /* 其它瀏覽器 */
    btn.addEventListener('click', handleClick, false);
}
</script>
註冊事件處理器 (續)

 優點: 除了有「使用 onEvent 成員」的優點之外,更可以註冊多
 個處理函式(處理器),隨時要抽離哪個都可以(利用
 removeEventListener 或 detachEvent)
 缺點: 該死的瀏覽器支援度不一。
事件處理器

其實就是一個 function,並且帶一個 event 參數(但是 IE 不會),
所以一般處理器會寫成這樣:

function handleClick(evt) {
  /* IE 會存在 window.event */
  evt = evt || window.event;
  ....
  ....
}
事件處理器 (續)

 阻擋預設事件的方式:

 <a href=quot;#quot; id=quot;dlg_btnquot;>Show Dialog</a>
 ....
 var btn = document.getElementById('dlg_btn');
 btn.addEventListener('click', function(evt) {
      evt = evt || window.event;
      ... /* TODO: show dialog */
      if (evt.preventDefault) { evt.preventDefault(); }
      else { window.event.returnValue = false; } /* for IE */
      return false;
 }, false);
 ...
AJAX
Asynchronous Javascript And XML

 瀏覽器端要與伺服器端溝通,得要經由 GET/POST 的方式送
 資料到伺服器,但如果只是需要小部份的改變,卻要用
 GET/POST 讓瀏覽器重新讀取整個網頁,耗費的成本太大。
   透過 XML HTTP Request 方式,利用 JavaScript 送出資料
   到伺服器上,並取得結果(不必重讀整個頁面)。
 Same Origin Policy (SOP): Ajax 只能把資料送給網頁的伺
 服器(不能送資料去別的網站)
AJAX 的應用

 Web mail 系統,刪除一封郵件不必重讀整頁,送出要刪除的
 信件資料即可。
 當使用者在填寫表單時,比方說用戶名稱,到伺服器上檢查是
 否有重覆的名稱。
 根據使用者的操作,立刻顯示結果或是回應。
 ...
使用 AJAX

 在 IE7 及 Firefox, Safari, Opera 等軟體中,可以直接使用
 XMLHttpRequest 物件來進行操作。但 IE6 以前得必須利
 用  ActiveX 物件來使用。

 var xhr;
 if (XMLHttpRequest){ /* 瀏覽器 內建 XMLHttpRequest */
   xhr = new XMLHttpRequest();
 } else if (ActiveXObject){ /* 使用 ActiveX 物件 */
   xhr = new ActiveXObject('Microsoft.XMLHTTP');
 } else {
   alert('您的瀏覽器不支援 AJAX');
 }
使用 AJAX -- 送出請求

 GET
 xhr = createXHR();
 xhr.open('GET', '/hello.php');
 xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      alert(xhr.responseText);
    }
 };
 xhr.send();


 POST
 var params='x=1&y=2';
 xhr = createXHR();
 xhr.open('POST', '/receive.php');
 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xhr.setRequestHeader('Content-length', params.length);
 xhr.send(params);
JavaScript Framework
為什麼要有 JavaScript Framework?

 簡化常用寫法的程式碼複雜度。
 儘可能地將瀏覽器支援問題包裝起來,讓你寫 code 時不用煩
 惱各個瀏覽器的問題。
 讓專業的來..
 ...
Prototype.js

一個以 Class 為基礎的 framework,Ruby-on-Rails 的預先配置
JavaScript 框架。

Prototype.js 的使用範例:
   取得網頁元素物件的 shortcut:
  // var p = document.getElementById('x');
  var p = $('x');

  方式的 DOM 操作:
  new Insertion.Before('result', '<h1>Result</h1>');
  簡易使用的 Ajax:
  new Ajax.Updater('result', '/hello.php');
Prototype.js (續)

 優點:
   在網路上可以找到不少範例。
   有 Script.aculo.us 套件作特效及簡易 UI
   有的 web framework (如 Rails)會提供 helper method,可以
   少寫一些 JavaScript code。
 缺點:
   framework 的 code size 大。
   加了新的 api 到原生的 String, Object, Array 中,用久了容
   易混淆哪些是原生的 method。
   Class-based 使得 JS 在執行期使用較多的記憶體。
Yahoo! User Interface (YUI)

  Yahoo! 開發團隊所維護的前端函式庫

  包含豐富的 UI 函式庫,也有一些 DOM, Event, AJAX 的函式
  庫,足以應付前端所有的需求。
  YUI 的使用:
    建立一個 YUI Button:
    var btn = new YAHOO.widget.Button('the_button');
    處理 event:
    btn.on('click', function(e) {
      ....
    });
Yahoo! User Interface (YUI)

  優點:
    文件豐富而完整,開發團隊不會突然消失。
    UI 介面豐富,而且幾乎適用於所有瀏覽器。
    UI 提供更換佈景主題的框架。
  缺點:
    對於物件處理方式不是很統一。
    code 架構繁雜,修改、擴充並不容易。
    文件雖然豐富,但秘技還是太多....
jQuery

 由 CSSQuery 這套 framework 而來,主要特色是把 CSS 選擇
 器帶進 JavaScript 中來取得元素。

 除了選擇器好用,jQuery 的設計架構更容易寫出輕巧的 code
 做複雜的事:

 $('body').eq(0)
 .append('<div class=quot;hiddenquot;>Hello, World</div>')
 .children('.hidden').css({color:'#d00'}).show('slow');
jQuery (續)

 優點:
   framework code size 非常小
   選擇器好用,而且相容於 CSS3
   速度飛快
   Google 有幫忙免費線上 host
 缺點:
   jQuery UI 還在努力中
   code 很容易寫得看不懂
範例討論
例1:Lightbox 效果

 情境: 按下一個按鈕,使畫面暗下,並且顯示出一個對話盒訊
 息。(對話盒內有一個按鈕可以關閉)
例2:檢 查表單輸入資料

在 Submit 前,先用 JavaScript 檢查表單的輸入資料。

注意: User 可能會把 JavaScript 停用,所以在 server 端還是要檢
查。
例3: 淡入淡出

設定某個元素淡入 (fade in), 淡出 (fade out)

  修改元素的 opacity
  利用 setInterval, clearInterval
  remove

Weitere ähnliche Inhalte

Was ist angesagt?

プログラマのためのテスト2
プログラマのためのテスト2プログラマのためのテスト2
プログラマのためのテスト2Kuniaki Igarashi
 
Hazrat Khalid Bin Waleed Book By Ataurrahman Noori
Hazrat Khalid Bin Waleed Book By Ataurrahman NooriHazrat Khalid Bin Waleed Book By Ataurrahman Noori
Hazrat Khalid Bin Waleed Book By Ataurrahman NooriAtaurrahman Noori
 
Написание DSL в Perl
Написание DSL в PerlНаписание DSL в Perl
Написание DSL в Perlmayperl
 
Benamazi ka anjam by maulana shakir ali noori
Benamazi ka anjam by maulana shakir ali nooriBenamazi ka anjam by maulana shakir ali noori
Benamazi ka anjam by maulana shakir ali nooriAtaurrahman Noori
 
藏漢對照菩提道次第廣論25(S5392 L)
藏漢對照菩提道次第廣論25(S5392 L)藏漢對照菩提道次第廣論25(S5392 L)
藏漢對照菩提道次第廣論25(S5392 L)pedmavajra
 
筆試(選擇題)
筆試(選擇題)筆試(選擇題)
筆試(選擇題)driver168
 
عشر کے احکام
عشر کے احکامعشر کے احکام
عشر کے احکامAhmed@3604
 
6 DOF of Rigid Body Equation of Motion 2
6 DOF of Rigid Body Equation of Motion 26 DOF of Rigid Body Equation of Motion 2
6 DOF of Rigid Body Equation of Motion 2kouhei1970
 
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974muzaffertahir9
 
Inventory Optimization
Inventory OptimizationInventory Optimization
Inventory OptimizationAdexa, Inc.
 
Manuale tecnico - Corbetta | Fia
Manuale tecnico - Corbetta | FiaManuale tecnico - Corbetta | Fia
Manuale tecnico - Corbetta | FiaCorbettaFia
 
藏漢對照菩提道次第廣論14(S5392 L)
藏漢對照菩提道次第廣論14(S5392 L)藏漢對照菩提道次第廣論14(S5392 L)
藏漢對照菩提道次第廣論14(S5392 L)pedmavajra
 
台灣老街小吃
台灣老街小吃台灣老街小吃
台灣老街小吃5045033
 

Was ist angesagt? (20)

プログラマのためのテスト2
プログラマのためのテスト2プログラマのためのテスト2
プログラマのためのテスト2
 
Hazrat Khalid Bin Waleed Book By Ataurrahman Noori
Hazrat Khalid Bin Waleed Book By Ataurrahman NooriHazrat Khalid Bin Waleed Book By Ataurrahman Noori
Hazrat Khalid Bin Waleed Book By Ataurrahman Noori
 
Написание DSL в Perl
Написание DSL в PerlНаписание DSL в Perl
Написание DSL в Perl
 
Satyanarayana Puja
Satyanarayana PujaSatyanarayana Puja
Satyanarayana Puja
 
Benamazi ka anjam by maulana shakir ali noori
Benamazi ka anjam by maulana shakir ali nooriBenamazi ka anjam by maulana shakir ali noori
Benamazi ka anjam by maulana shakir ali noori
 
A* Algorithm
A* AlgorithmA* Algorithm
A* Algorithm
 
Excel
ExcelExcel
Excel
 
藏漢對照菩提道次第廣論25(S5392 L)
藏漢對照菩提道次第廣論25(S5392 L)藏漢對照菩提道次第廣論25(S5392 L)
藏漢對照菩提道次第廣論25(S5392 L)
 
屏東
屏東屏東
屏東
 
筆試(選擇題)
筆試(選擇題)筆試(選擇題)
筆試(選擇題)
 
2008 花東三天兩日遊 計劃書 導覽手冊
2008 花東三天兩日遊 計劃書 導覽手冊2008 花東三天兩日遊 計劃書 導覽手冊
2008 花東三天兩日遊 計劃書 導覽手冊
 
عشر کے احکام
عشر کے احکامعشر کے احکام
عشر کے احکام
 
6 DOF of Rigid Body Equation of Motion 2
6 DOF of Rigid Body Equation of Motion 26 DOF of Rigid Body Equation of Motion 2
6 DOF of Rigid Body Equation of Motion 2
 
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974
Friday Sermon Dilivered by Hazrat Mirza Nasir Ahmed (RA) 12 Apr 1974
 
2008IFLA report
2008IFLA report2008IFLA report
2008IFLA report
 
Inventory Optimization
Inventory OptimizationInventory Optimization
Inventory Optimization
 
Manuale tecnico - Corbetta | Fia
Manuale tecnico - Corbetta | FiaManuale tecnico - Corbetta | Fia
Manuale tecnico - Corbetta | Fia
 
藏漢對照菩提道次第廣論14(S5392 L)
藏漢對照菩提道次第廣論14(S5392 L)藏漢對照菩提道次第廣論14(S5392 L)
藏漢對照菩提道次第廣論14(S5392 L)
 
Al haadi cropped
Al haadi croppedAl haadi cropped
Al haadi cropped
 
台灣老街小吃
台灣老街小吃台灣老街小吃
台灣老街小吃
 

Andere mochten auch

08 06 Petley Round Table
08 06 Petley Round Table08 06 Petley Round Table
08 06 Petley Round TableDr_Dave
 
Bubbles12whole
Bubbles12wholeBubbles12whole
Bubbles12wholeRoom6stjos
 
Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計Eric ShangKuan
 
An Introduction to GAEO web framework
An Introduction to GAEO web frameworkAn Introduction to GAEO web framework
An Introduction to GAEO web frameworkEric ShangKuan
 
08 06 Xian Saito Talk 2003v
08 06 Xian Saito Talk 2003v08 06 Xian Saito Talk 2003v
08 06 Xian Saito Talk 2003vDr_Dave
 

Andere mochten auch (6)

Microsoft and jQuery
Microsoft and jQueryMicrosoft and jQuery
Microsoft and jQuery
 
08 06 Petley Round Table
08 06 Petley Round Table08 06 Petley Round Table
08 06 Petley Round Table
 
Bubbles12whole
Bubbles12wholeBubbles12whole
Bubbles12whole
 
Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計
 
An Introduction to GAEO web framework
An Introduction to GAEO web frameworkAn Introduction to GAEO web framework
An Introduction to GAEO web framework
 
08 06 Xian Saito Talk 2003v
08 06 Xian Saito Talk 2003v08 06 Xian Saito Talk 2003v
08 06 Xian Saito Talk 2003v
 

Mehr von Eric ShangKuan

運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式
運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式
運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式Eric ShangKuan
 
Introducing .NET Core Open Source
Introducing .NET Core Open SourceIntroducing .NET Core Open Source
Introducing .NET Core Open SourceEric ShangKuan
 
Azure machine learning overview
Azure machine learning overviewAzure machine learning overview
Azure machine learning overviewEric ShangKuan
 
透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 AppsEric ShangKuan
 
Metro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewMetro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewEric ShangKuan
 
Building Python Applications on Windows Azure
Building Python Applications on Windows AzureBuilding Python Applications on Windows Azure
Building Python Applications on Windows AzureEric ShangKuan
 
Tuning Web Performance
Tuning Web PerformanceTuning Web Performance
Tuning Web PerformanceEric ShangKuan
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In PyEric ShangKuan
 
The Google App Engine Oil Framework
The Google App Engine Oil FrameworkThe Google App Engine Oil Framework
The Google App Engine Oil FrameworkEric ShangKuan
 

Mehr von Eric ShangKuan (13)

運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式
運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式
運用 Azure Custom Vision 輕鬆開發智慧視覺應用程式
 
Introducing .NET Core Open Source
Introducing .NET Core Open SourceIntroducing .NET Core Open Source
Introducing .NET Core Open Source
 
In
InIn
In
 
Azure machine learning overview
Azure machine learning overviewAzure machine learning overview
Azure machine learning overview
 
透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps
 
Metro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' ViewMetro Style Apps from C++ Developers' View
Metro Style Apps from C++ Developers' View
 
Building Python Applications on Windows Azure
Building Python Applications on Windows AzureBuilding Python Applications on Windows Azure
Building Python Applications on Windows Azure
 
Tuning Web Performance
Tuning Web PerformanceTuning Web Performance
Tuning Web Performance
 
Intro To Google Maps
Intro To Google MapsIntro To Google Maps
Intro To Google Maps
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Intro. to CSS
Intro. to CSSIntro. to CSS
Intro. to CSS
 
jQuery Tutorial
jQuery TutorialjQuery Tutorial
jQuery Tutorial
 
The Google App Engine Oil Framework
The Google App Engine Oil FrameworkThe Google App Engine Oil Framework
The Google App Engine Oil Framework
 

Intro. to JavaScript

  • 1. JavaScript 快速上手 上官林傑 (ericsk)
  • 2. 課程大綱 JavaScript 簡介 基本語法 用 JavaScript 控制網頁元素 (DOM) 事件處理 (Event) Ajax JavaScript Framework 簡介 範例討論
  • 4. JavaScript 簡介 一種程式語言,與 Java 無關 ,而且並不是簡單 的語言! 直譯式程式語言,由瀏覽器的 JS 引擎執行 瀏覽器支援性問題 動態(弱)資料型態 可以動態執行程式碼 -- eval() 單一執行緒 運用 timer 作非同步多工 目前最多的應用在網頁設計上。 script 在瀏覽器上執行,所以 user 會看到全部的程式碼 千萬不要放重要資訊在 JS 的程式碼裡 上線環境下,js 檔案(或 CSS檔案)最好「壓縮」過 減少傳輸量
  • 5. JavaScript 的使用 你可以: 改變網頁元素的內容、樣式 處理使用者在網頁上的動作(點擊、按鍵等) 與網站的 Server 溝通(AJAX) ... 你不行: 儲存或讀取使用者電腦裡的資料(檔案、記憶體等) 與其它網站建立連線(SOP) 編修網頁上的圖片(resize, rotate)
  • 6. 在網頁中使用 JavaScript 用 <script> 標籤: <script type=quot;text/javascriptquot;> window.alert('hello, world!'); </script> 寫在 *.js 檔案裡再引入: <script type=quot;text/javascriptquot; src=quot;hello.jsquot;></script>
  • 7. JavaScript 的偵錯(debug)方式 用 window.alert() 印出變數的值,或是用來判斷程式是 否執行到此。 好處:任何瀏覽器都支援 缺點:如果在迴圈中 debug,彈出視窗按不完... 利用 Firefox 的 firebug 套件 好處:功能很強 缺點:只能在 firefox 上使用。 利用 YUI Logger 好處:不限瀏覽器 缺點:擋在畫面上比較麻煩
  • 8. 基本語法 -- 注意事項 程式碼的字母大小寫有別 (case-sensitive) WHILE(a != 0) { while (a != 0) { .... .... a = a - 1; a = a - 1; } } 可以不加 ; 在結尾 -- 一行一個敘述句 a=2 a = 2; b = 3; 註解可以用 /* ... */ 或是 = 3 b //
  • 9. 變數 (Variable) 用 var 關鍵字宣告,不過也可以省略 重覆宣告OK,會採用最新的 由英文字母、數字及 _ 組成,但首字不可是數字 (可以用 $) 變數的有效範圍 基本資料型態 數值: 3, 20, 23.5 字串: 'aaa', quot;bbbquot; 布林: true, false 空值、未定義: null, undefined NaN
  • 10. 變數基本運算 數字 基本運算: +, -, *, /, % 邏輯運算:==, &&, || 字串的 + 運算 quot;abcquot; + quot;abcquot; = quot;abcabcquot; quot;3quot; + 3 = quot;33quot; parseInt(quot;3quot;) + 3 = 6 布林 值 0, null, undefined, false, quot;quot;, NaN 在邏輯判斷上 都是 false 非以上值全為 true
  • 11. 流程控制 - 判斷式 (if) 使用 if, else if, else 關鍵字。 用法: if (判斷式1) { ... } else if (判斷式2) { ... } else { ... } 如果只有一行敘述,也可以省略 {}
  • 12. 流程控制 - 判斷式 (switch) switch (變數) { case 值1: .... 如果沒有 break; 則流程會繼續 break; 到下一個 case case 值2: ... break; ... default: ... }
  • 13. 流程控制 - 迴圈 (do while/while) 用來重覆執行某一段程式碼 var n = 10, i = 10; while (i < n) { i = i + 1; } // 這裡 i == 10 var n = 10, i = 10; do { i=i +1 } while (i < n); // 這裡 i == 11
  • 14. 流程控制 - 迴圈 (for) 1 2 5 4 for (敘述句; 判斷式; 敘述句) { 3 ..... } 上一頁的例子可以寫成相同的 for 迴圈: var n = 10, i; for (i = 0; i < n; i = i + 1) { ; } // 這裡 i == 10
  • 15. 自訂函數 為了結構化函式、重覆利用程式碼, 例: 可以自訂函數 function plus2(x) { function 函式名稱(參數列...) { return x + 2; } ... } var a = 10; b = plus2(a); 也可以寫成: // b 這裡 值為 12 var 函式名稱 = function(參數列) { ..... }
  • 16. 匿名函數 (anonymous function) 當某些 API 需要傳入一個 function 作為參數時,如果只用一次也 可以直接傳入一個匿名函數。 /* 每 1 秒顯示一次訊息 */ var timerId = setInterval(function(){alert('hi');}, 1000); /* 清除 timer */ clearInterval(timerId); /* 1秒後顯示 */ setTimeout(funciton(){alert('!!');}, 1000);
  • 17. 進階資料型態: 陣列 (Array) 可以擺放連續資料的結構,再透過 index 的方式取得或設定資 料的內容。 生成陣列的方式: var a = [123, quot;abcdquot;]; var a = []; a[0] = 123; var a = new Array(123, quot;abcdquot;); a[1] = quot;abcdquot;;
  • 18. 使用陣列 (Array) var a = new Array(123, 'abc', 456); 取得陣列長度: a.length -> 3 陣列相關函式:(以下例子各不相關,a 都是 (123, 'abc', 456) a.concat([100, 200]) -> [123, 'abc', 456, 100, 200] a.push(300) -> [123, 'abc', 456, 300] a.pop() -> [123, 'abc'] 並傳回 456 a.shift() -> ['abc', 456] a.unshift(789) -> [789, 123, 'abc', 456] a.reverse() -> [456, 'abc', 123] a.sort() -> [123, 456, 'abc'] a.slice(0, 2) -> [123, 'abc'] a.join(',') -> quot;123,abc,456quot;
  • 19. JSON - JavaScript Object Notation JavaScript 中用來表示物件的資料結構。 var rect = { name: 'rectangle 1', width: 200, height: 100, area: function() { return this.width * this.height; } }; r.area() -> 20000 r.width = 100; r.area() -> 10000
  • 21. 取得文件元素 getElementById(id) 根據為標籤設的 id 來取得該元素,如: var p = document.getElementById('panel'); <div id=quot;panelquot;></div> <div id=quot;sidebarquot;></div> p.innerHTML = '<h1>hello</h1>'; <div id=quot;panelquot;><h1>hello</h1></div> <div id=quot;sidebarquot;></div>
  • 22. 取得文件元素 (續) getElementsByTagName(name) 根據為標籤名稱 來取得該元素,如: var panels = document.getElementsByTagName('div'); <div></div> <p>aaa</p> <div></div> for (var i in panels) { panels[i].innerHTML = 'hello'; } <div>hello</div> <p>aaa</p> <div>hello</div>
  • 23. 文件物件模型 (DOM) 把結構化的文件(如:HTML, XML)的每一個標籤看作是一個物件, 並且有階層的概念。 <div> div <p id=quot;xquot;>Lorem ipsum dolor sit</p> <ul> <li>abcd</li> p ul <li>1234</li> </ul> </div> li li
  • 24. 文件物件模型 (DOM) (續) var p = document.getElementById('x'); q = p.parentNode -> <div> q.childNodes -> ['n ', <p>, 'n ', <ul>, 'n'] p.getAttribute('id') -> 'x' p.setAttribute('title', 'hello') -> <p id=quot;xquot; title=quot;helloquot;> p.removeAttribute('id') -> <p title=quot;helloquot;>
  • 25. 改變文件元素的樣式 透過文件元素的 style 屬性來改變該元素的樣式,效果相當 於在標籤裡的 style=quot;quot; 一樣 var p = document.getElementById('x'); p.style.color = '#ff0000'; p.style.backgroundColor = '#00ffff'; CSS 屬性名稱如果有 - 的部份,就要把 - 去 掉,並且將下一字母大寫,如 text-align 就 要改成 textAlign
  • 26. 產生/移除文件元素 document.createElement(tagName ) 用來產生新的元素 新增 var newDiv = document.createElement('div'); newDiv.id = 'new_d'; newDiv.innerHTML = 'hello'; document.body.appendChild(newDiv); 移除 var n = document.getElementById('new_d'); document.body.removeChild(n);
  • 27. 產生/移除文件元素 (續) 插入 var p = document.getElementById('x'); var newDiv = document.createElement('div'); newDiv.id = 'new_d'; newDiv.innerHTML = 'hello'; document.body.insertBefore(newDiv, p);
  • 29. 事件 (event) 瀏覽器會在網頁發生某些狀態改變、或是使用者的某些動作時產 生「事件」(event),透過 JavaScript 你可以處理這些事件發 生時,要做哪些事情。比方說: 當使用者按下某個按鈕時 當滑鼠游標移過某個元素時 當整個網頁都載入時 ...
  • 30. 元素標籤的 on Event 屬性 指定某個元素的 onXXXX 屬性 <input type=quot;buttonquot; value=quot;按我quot; onclick=quot;alert('我被按 了!');quot; /> 這種方法雖然簡單快速,但難以處理複雜的狀況,程式碼也不 好維護,同樣的動作無法重覆利用。
  • 31. 元素物件的 on Event 成員 改寫該元素物件的 onXXXX 成員: <input type=quot;buttonquot; id=quot;btnquot; value=quot;按我quot; /> <script type=quot;text/javascriptquot;> var btn = document.getElementById('btn'); btn.onclick = function(evt) { alert('被按了..'); }; </script>
  • 32. 元素物件的 on Event 成員 (續) 優點: 可以自己寫好事件處理的函式,然後再套用,可重覆利 用也容易維護。更重要的是將 HTML/JavaScript 抽離。 缺點: 如果同一個事件要做很多不同的事,就要自己處理要記 得做哪些事,然後在 onEvent 中全部做完。(單一抽換也麻 煩) function hand1(evt) { ... }; function hand2(evt) { ... }; x.onmouseover = function(evt) { hand1(evt); hand2(evt); };
  • 33. 註冊事件處理器 對物件註冊處理器 (利用 addEventListener 或 attachEvent) <script type=quot;text/javascriptquot;> function handleClick(evt) { alert('被按了'); }; var btn = document.getElementById('btn'); if (btn.attachEvent) { /* 為了 IE */ btn.attachEvent('onclick', handleClick); } else { /* 其它瀏覽器 */ btn.addEventListener('click', handleClick, false); } </script>
  • 34. 註冊事件處理器 (續) 優點: 除了有「使用 onEvent 成員」的優點之外,更可以註冊多 個處理函式(處理器),隨時要抽離哪個都可以(利用 removeEventListener 或 detachEvent) 缺點: 該死的瀏覽器支援度不一。
  • 35. 事件處理器 其實就是一個 function,並且帶一個 event 參數(但是 IE 不會), 所以一般處理器會寫成這樣: function handleClick(evt) { /* IE 會存在 window.event */ evt = evt || window.event; .... .... }
  • 36. 事件處理器 (續) 阻擋預設事件的方式: <a href=quot;#quot; id=quot;dlg_btnquot;>Show Dialog</a> .... var btn = document.getElementById('dlg_btn'); btn.addEventListener('click', function(evt) { evt = evt || window.event; ... /* TODO: show dialog */ if (evt.preventDefault) { evt.preventDefault(); } else { window.event.returnValue = false; } /* for IE */ return false; }, false); ...
  • 37. AJAX
  • 38. Asynchronous Javascript And XML 瀏覽器端要與伺服器端溝通,得要經由 GET/POST 的方式送 資料到伺服器,但如果只是需要小部份的改變,卻要用 GET/POST 讓瀏覽器重新讀取整個網頁,耗費的成本太大。 透過 XML HTTP Request 方式,利用 JavaScript 送出資料 到伺服器上,並取得結果(不必重讀整個頁面)。 Same Origin Policy (SOP): Ajax 只能把資料送給網頁的伺 服器(不能送資料去別的網站)
  • 39. AJAX 的應用 Web mail 系統,刪除一封郵件不必重讀整頁,送出要刪除的 信件資料即可。 當使用者在填寫表單時,比方說用戶名稱,到伺服器上檢查是 否有重覆的名稱。 根據使用者的操作,立刻顯示結果或是回應。 ...
  • 40. 使用 AJAX 在 IE7 及 Firefox, Safari, Opera 等軟體中,可以直接使用 XMLHttpRequest 物件來進行操作。但 IE6 以前得必須利 用  ActiveX 物件來使用。 var xhr; if (XMLHttpRequest){ /* 瀏覽器 內建 XMLHttpRequest */ xhr = new XMLHttpRequest(); } else if (ActiveXObject){ /* 使用 ActiveX 物件 */ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } else { alert('您的瀏覽器不支援 AJAX'); }
  • 41. 使用 AJAX -- 送出請求 GET xhr = createXHR(); xhr.open('GET', '/hello.php'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } }; xhr.send(); POST var params='x=1&y=2'; xhr = createXHR(); xhr.open('POST', '/receive.php'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Content-length', params.length); xhr.send(params);
  • 43. 為什麼要有 JavaScript Framework? 簡化常用寫法的程式碼複雜度。 儘可能地將瀏覽器支援問題包裝起來,讓你寫 code 時不用煩 惱各個瀏覽器的問題。 讓專業的來.. ...
  • 44. Prototype.js 一個以 Class 為基礎的 framework,Ruby-on-Rails 的預先配置 JavaScript 框架。 Prototype.js 的使用範例: 取得網頁元素物件的 shortcut: // var p = document.getElementById('x'); var p = $('x'); 方式的 DOM 操作: new Insertion.Before('result', '<h1>Result</h1>'); 簡易使用的 Ajax: new Ajax.Updater('result', '/hello.php');
  • 45. Prototype.js (續) 優點: 在網路上可以找到不少範例。 有 Script.aculo.us 套件作特效及簡易 UI 有的 web framework (如 Rails)會提供 helper method,可以 少寫一些 JavaScript code。 缺點: framework 的 code size 大。 加了新的 api 到原生的 String, Object, Array 中,用久了容 易混淆哪些是原生的 method。 Class-based 使得 JS 在執行期使用較多的記憶體。
  • 46. Yahoo! User Interface (YUI) Yahoo! 開發團隊所維護的前端函式庫 包含豐富的 UI 函式庫,也有一些 DOM, Event, AJAX 的函式 庫,足以應付前端所有的需求。 YUI 的使用: 建立一個 YUI Button: var btn = new YAHOO.widget.Button('the_button'); 處理 event: btn.on('click', function(e) { .... });
  • 47. Yahoo! User Interface (YUI) 優點: 文件豐富而完整,開發團隊不會突然消失。 UI 介面豐富,而且幾乎適用於所有瀏覽器。 UI 提供更換佈景主題的框架。 缺點: 對於物件處理方式不是很統一。 code 架構繁雜,修改、擴充並不容易。 文件雖然豐富,但秘技還是太多....
  • 48. jQuery 由 CSSQuery 這套 framework 而來,主要特色是把 CSS 選擇 器帶進 JavaScript 中來取得元素。 除了選擇器好用,jQuery 的設計架構更容易寫出輕巧的 code 做複雜的事: $('body').eq(0) .append('<div class=quot;hiddenquot;>Hello, World</div>') .children('.hidden').css({color:'#d00'}).show('slow');
  • 49. jQuery (續) 優點: framework code size 非常小 選擇器好用,而且相容於 CSS3 速度飛快 Google 有幫忙免費線上 host 缺點: jQuery UI 還在努力中 code 很容易寫得看不懂
  • 51. 例1:Lightbox 效果 情境: 按下一個按鈕,使畫面暗下,並且顯示出一個對話盒訊 息。(對話盒內有一個按鈕可以關閉)
  • 52. 例2:檢 查表單輸入資料 在 Submit 前,先用 JavaScript 檢查表單的輸入資料。 注意: User 可能會把 JavaScript 停用,所以在 server 端還是要檢 查。
  • 53. 例3: 淡入淡出 設定某個元素淡入 (fade in), 淡出 (fade out) 修改元素的 opacity 利用 setInterval, clearInterval remove