SlideShare a Scribd company logo
1 of 46
Download to read offline
jQuery Tutorial

  上官林傑 (ericsk)
   2008/07/25
課程大綱

JavaScript Framework
jQuery 設計概念
jQuery 選擇器及 DOM 基本操作
事件處理及 Ajax
特效與 UI
實作練習
quot; If I have seen further, it is
by standing on the shoulders
of Giants. quot;
Issac Newton , 1676.
Why JavaScript Framework?

 JavaScript 太難寫了!
    有 framework 可以減輕負擔,何樂而不為?
 各個瀏覽器各自為政 (其實也就 MSIE 比較不合群一點)
    不要再浪費時間在處理跨瀏覽器的問題了。
 站在巨人的肩膀上,讓專業的來
   牛頓都跟你說了...
 容易有範本可以抄 (好工程師不要學...)
     嗯,免得東抄西抄 code 更難維護
 ...
Why jQuery?

 好學好用,重點是它還很輕巧
   以物件為中心,可以是主格也可以是受格。
         e.g., 有 append 也可以 appendTo
       完整的源碼大小(壓縮後傳輸)僅僅 16 Kb (版本1.2.6)

 超棒超快速的選擇器
       完全支援 CSS 3 及 XPath 選擇器,容易操作網頁上的物件。
       一次呼叫便套用至所有被選擇到的元素。
 Open Source & Google hosted
       不用自己煩惱更換版本或是擺放 jQuery 的位址。
 ...
jQuery 的設計架構及使用
jQuery 能做的事...

 新增或移除 DOM 物件(網頁上的元素)
 更改網頁元素的樣式及內容
 處理事件
 產生特效或動畫
 Ajax
 ....
jQuery 的設計概念

 jQuery 是用來操作選擇器的物件,也是整套 framework 的
 prototype
    所有東西都是 jQuery,也可以簡單寫作 $。
 所有 API 的回傳值都是 jQuery 物件及陣列
    jQuery 物件 -> 可以接 combo 技
        e.g.,
     $('<h1>test</h1>').css({color:'red'}).attr({id:
     'title'}).appendTo($('body'));
   陣列 -> 一個動作套用到全部
     e.g.,
     $('.items').addClass('selected');
使用 jQuery

1. 在 http://jquery.com/ 下載最新的 jquery*.js 檔案,然後跟你的
   project 擺在一起並且引入。
   e.g.,
  <script type=quot;text/javascriptquot; src=quot;jquery-1.2.6.min.
  jsquot;></script>
2. 直接使用 Google host 的 jQuery
  <script type=quot;text/javascriptquot; src=quot;http://ajax.
  googleapis.com/ajax/libs/jquery/1/jquery.min.jsquot;
  ></script>
jQuery Hello World

$('<h1>Hello, world</h1>').appendTo($('body'));



作了什麼事?
 1. 動態產生了一個 <h1>Hello, world</h1>,並且把它變成 jQuery
    物件。
 2. 使用 jQuery.appendTo API 將之插入到 body tag 的最後面。
jQuery 選擇器

jQuery 的選擇器包括:
  一段 HTML,如果沒有 match 到則會產生新的。
     $('<div>test</div>')

  標籤名
     $('body')
  CSS 3 選擇器
     $('ul > li.selected')

  XPath
     $('a[@href^=http://www.cht]')
jQuery 選擇器(續)

 搭配選擇器一同服用的 filter
 $('ul > li:even'), $('ul > li:first-child')

 表單特殊的選擇器
 $(':checked'), $(':input')
 除了直接選擇之外,也可以加入 context:
 $('div', '#panel')
jQuery 陣列

 因為 jQuery 選擇後都是回傳「陣列」,所以可以用陣列長度是
 否大於 0 來判斷是不是有選到東西:

 if ($('.checked').length == 0) {
   alert('您還沒有勾選');
 }
 針對每個選到的元素操作:
    如果是 jQuery API,直接套用即可。
    否則:
    $('.selected').each(function(index , domElem ) {
        ....
    });
jQuery 陣列(續)

 雖然回傳的都是 jQuery 物件,但可以用 get([index]) 取回
 DOM Element。

 $('#nick').get(0) == document.getElementById('nick')

 也可以用 index() 來查該 DOM element/jQuery object 在
 陣列中的位置。
    1.2.3以前只能查 DOM element,後來我發了一個 ticket 請
    jQuery team 支援查 jQuery object
讀取、修改元素 內容

 使用 html() 或 text() 來塞一段或讀取 HTML code 或 text
 在選到的元素。
   沒帶參數是讀出來:
   var content = $('#test').html();

   加了參數是修改:
   $('#test').html('modified content');
 很多 jQuery 的 API 都有上述的設計(getter/setter)
讀取、修改元素 內容(續)

<div id=quot;fooquot;>abcdefg</div>


var c = $('#foo').html();
// c 的值為 quot;abcdefgquot;
...
...
// 把 #foo 的內容改成 hij
$('#foo').html('hij');



<div id=quot;fooquot;>hij</div>
元素屬性

用 attr() 來處理元素中的屬性
 一樣有前述 getter/setter 的設計,不過參數可以帶字串或是
 JSON object:
                           // 取得 id 的 值
 $(...).attr('id');
 $(...).attr('id', 'foo'); // 將 id 改成 foo
 一次設定多個屬性
 $('.foo').attr({rel: 'bar', title: 'show me'});



  <div class=quot;fooquot;>...</div>
  <div class=quot;fooquot;>...</div>



 <div class=quot;fooquot; rel=quot;barquot; title=quot;show mequot;>...</div>
 <div class=quot;fooquot; rel=quot;barquot; title=quot;show mequot;>...</div>
元素樣式

用 css() 修改樣式
  效果如同直接修改 style 屬性,所以要用 style 的名稱
  (backgroun-color -> backgroundColor)
  $('.foo').css({textAlign: 'center', color: 'red'});


  <div class=quot;fooquot;>...</div>



  <div class=quot;fooquot; style=quot;text-align:center;color:
  red;quot;>...</div>
元素的 class

 利用 addClass() 或 removeClass() 來新增移除 class
   若是直接修改 class 屬性,要自行處理字串。

    $('.foo').addClass('highlight');

    <div class=quot;fooquot;>...</div>



    <div class=quot;foo highlightquot;>...</div>


    $('.foo').removeClass('foo');
    <div class=quot;foo highlightquot;>...</div>



    <div class=quot;highlightquot;>...</div>
DOM 操作

 內部插入元素:
 append(), appendTo() -- 插入最後
 prepend(), prependTo() -- 插入最前

$('.foo').append('<b>hello</b>');   $('<em>test</em>').prependTo($('#x'));

                                    <div id=quot;xquot;>
 <div class=quot;fooquot;>
                                       ...
    ...
                                    </div>
 </div>




                                     <div id=quot;xquot;>
 <div class=quot;fooquot;>
                                        <em>test</em>
   ...
                                        ...
   <b>hello</b>
                                     </div>
 </div>
DOM 操作(續)

 外部插入元素:
   wrap()
   $('.foo').wrap('<p id=quot;panelquot;>');

   <div class=quot;fooquot;>...</div>



    <p id=quot;panelquot;>
    <div class=quot;fooquot;>...</div>
    </p>
DOM 操作(續)

 前後插入
   before(), insertBefore()
   after(), insertAfter()

 $('.foo').after('<img src=quot;load.gifquot; alt=quot;loadingquot;/>');

  <div class=quot;fooquot;>...</div>



  <div class=quot;fooquot;>...</div>
  <img src=quot;load.gifquot; alt=quot;loadingquot;/>




    更多 jQuery DOM 操作請參考  http://docs.jquery.com/Manipulation
DOM 走訪 (Traversing)

 在選擇某元素後,再透過 traverse/filter 的 API 來「再選擇」其
 它的元素。
 前後一個
   $(...).prev([filter] );
   $(...).next([filter] );



  $('.foo').next();


  <div class=quot;fooquot;>...</div>
  <img src=quot;load.gifquot; alt=quot;loadingquot;/>
DOM 走訪 (Traversing)

 親子關係
   $(...).parent([filter] );
   $(...).children([filter] );
   $(...).siblings([filter] );
 篩選器
   $(...).eq(index );
   $(...).filter([filter] );




    更多 DOM 走訪 操作請參考  http://docs.jquery.com/Traversing
事件(Event)處理
jQuery 的事件處理

 jQuery Events API 除了可以用一致的方式註冊事件處理器之
 外,也
   統一了 event object
   可以方便 trigger (自訂) 事件
   可以暫時開關事件處理器
   ...
 類似其它 API 的 getter/setter 的方式,但是
   傳入參數時,是傳入一個事件處理器
   若沒傳參數,則是 trigger 該事件
註冊事件處理器

處理 click 事件:

  $(...).click(function(evt) {
      alert('clicked');
  });

或是

  $(...).bind('click', function(evt) {
      alert('clicked');
  });
事件處理器(續)

 只做一次:
 $(...).one('click', funciton(e) { ... });

 移除處理器:
 $(...).unbind('click');
觸發事件

對某元素觸發 mouseover 事件:
$(...).mouseover();

或是
$(...).trigger('mouseover');
自訂事件

利用 bind 註冊自己的事件:
$(...).bind('dlg-open', function(e) { .... });

利用 trigger 來觸發
$(...).trigger('dlg-open');

利用 unbind 來移除
$(...).unbind('dlg-open');
onload shortcut

  在整頁都讀取完才做事
    處理 window.onload 的 event
    在 jQuery 中可以直接寫:

    $(function() {
      ....
    });

    即表示該 function 會在整頁讀完之後才運作。
AJAX
jQuery AJAX API

 專門用來處理 Ajax 的動作,可以直接使用 $.ajax() 來使用,
 再依照需求修改參數。
 有 $.get(), $.post(), $.load() 這些 shortcut 可以使用
 會自動觸發 ajax**** 事件,其它元素可以註冊這些事件的處
 理器。
$.ajax
$.ajax({
 // 用來指定要 request 的 URL
 url: '/foo.php',
 // 是要用 GET/POST 的方式作 request
 type: 'post',
 // request 的資料
 data: { ... },
 // 回傳的資料型態,會影響 success callback 的參數
  dataType: 'json',
 // 是否要 cache 住 response
 cache: false,
 // 在 ajax 發起 request 前呼叫
 beforeSend: function() { .... },
 // ajax 發生錯誤時呼叫
 error: function(xhr) { ... },
 // 成功完成 reuqest 時呼叫
 success: function(resp) { ... },
 // 最後呼叫
  complete: function(xhr) { ... }
});
範例:送出需求後更改某區域 內容

 $.ajax({
     url: 'foo.php',
     data: {x: 'abc', y: 123},
     success: function(resp) {
          $('#bar').html(resp);
     }
 });

或是
 $('#bar').load('foo.php', {x: 'abc', y: 123});
jQuery 自訂 ajax 事件

 透過註冊這些事件的處理器,當 ajax 在進行時,會依照進行的
 狀況驅動適當的事件

 有 ajaxStart, ajaxSend, ajaxStop, ajaxError,
 ajaxSuccess, ajaxComplete 這些自訂的 ajax 事件。
特效及 UI
jQuery 預設的特效

 預設在 jQuery 的函式庫中提供了基本常見的特效:
   顯示或消失(show、hide)
   向上或向下捲動(slideUp、slideDown)
   淡入或淡出(fadeIn、fadeOut、fadeTo)
 也可以自己設計特效。
   使用 animates()
jQuery UI

 http://ui.jquery.com/
 另外一組團隊基於 jQuery 所設計的 UI widget,網站上可以客
 製化需求下載 javascript 檔案來使用。
 也可以到 jQuery UI theme roller 網站選擇或設計自己的
 theme (CSS) 來改善 UI 美觀。
   http://ui.jquery.com/themeroller
自己寫 jQuery plugin
寫 jQuery plugin

  好處:重覆利用自己的 code,分享給團隊開發者一起使用。
  方法:
    定義在 $.fn 下
    符合 jQuery-style 來寫作
      API 要套用到「所有」被選擇到的元素。
      記得傳回 jQuery 陣列。
    注意儘量不要寫出會產生衝突的 code
      避免定義容易重覆的名稱。
    從別人的 code 中學習
      http://plugins.jquery.com/
套用至「所有」被選擇到的元素

 利用 $.each

 $.fn.foo = function({
   return this.each(function() {
     // TODO: 你要做的事
   });
 });
包裝 plugin

 避免寫出與其它 js 檔案相衝 code
 (function($){

  ....

 })(jQuery);

 如果能用 JSMin 或 YUI Compressor 壓縮一下也不錯。
結論
請愛用 jQuery

 讓 JavaScript 變好寫了(咦?)
 解決了不少跨瀏覽器間的問題。
 用了公認好用的 framework,在維護上也比較輕鬆。
 code 小、速度快。
 ...
線上資源

官方網站 :  http://jquery.com/
專案網站 :  http://code.google.com/p/jqueryjs/
jQuery UI: http://ui.jquery.com/
中文 jQuery 討論群組:
http://groups.google.com/group/jquery-

More Related Content

What's hot

Lets Enjoy C#!
Lets Enjoy C#!Lets Enjoy C#!
Lets Enjoy C#!
将 高野
 
Prestations et aides sociales, le dérapage incontrôlé
Prestations et aides sociales, le dérapage incontrôléPrestations et aides sociales, le dérapage incontrôlé
Prestations et aides sociales, le dérapage incontrôlé
Fondation iFRAP
 
مختارات من النثر العربي اختارها ادونيس
مختارات من النثر العربي اختارها ادونيسمختارات من النثر العربي اختارها ادونيس
مختارات من النثر العربي اختارها ادونيس
Mustafa Saad
 
Controlling globalweatheroct01
Controlling globalweatheroct01Controlling globalweatheroct01
Controlling globalweatheroct01
Clifford Stone
 
ديوان الشعر العربي الامارات وقطر وعمان
ديوان الشعر العربي الامارات وقطر وعمانديوان الشعر العربي الامارات وقطر وعمان
ديوان الشعر العربي الامارات وقطر وعمان
Mustafa Saad
 

What's hot (19)

Написание DSL в Perl
Написание DSL в PerlНаписание DSL в Perl
Написание DSL в Perl
 
Lets Enjoy C#!
Lets Enjoy C#!Lets Enjoy C#!
Lets Enjoy C#!
 
1046
10461046
1046
 
雪兰莪煤炭山集群学校90周年校庆纪念-李振和. 28 Nov 2010-SRJK (C) Chap Khuan Batu Arang, Selangor-...
雪兰莪煤炭山集群学校90周年校庆纪念-李振和. 28 Nov 2010-SRJK (C) Chap Khuan Batu Arang, Selangor-...雪兰莪煤炭山集群学校90周年校庆纪念-李振和. 28 Nov 2010-SRJK (C) Chap Khuan Batu Arang, Selangor-...
雪兰莪煤炭山集群学校90周年校庆纪念-李振和. 28 Nov 2010-SRJK (C) Chap Khuan Batu Arang, Selangor-...
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 
極める routes.php
極める routes.php極める routes.php
極める routes.php
 
umrah ka asan tariqa (hanfi) by Dr.hafiz Muhammad naeem
umrah ka asan tariqa (hanfi)  by Dr.hafiz  Muhammad naeemumrah ka asan tariqa (hanfi)  by Dr.hafiz  Muhammad naeem
umrah ka asan tariqa (hanfi) by Dr.hafiz Muhammad naeem
 
ملخص كتاب قوة التركيز لمؤلفه جاك كانفيلد
ملخص كتاب قوة التركيز لمؤلفه جاك كانفيلدملخص كتاب قوة التركيز لمؤلفه جاك كانفيلد
ملخص كتاب قوة التركيز لمؤلفه جاك كانفيلد
 
文化大學 管理數位學習碩士在職專班招生-詹翔霖副教授
文化大學 管理數位學習碩士在職專班招生-詹翔霖副教授文化大學 管理數位學習碩士在職專班招生-詹翔霖副教授
文化大學 管理數位學習碩士在職專班招生-詹翔霖副教授
 
Prestations et aides sociales, le dérapage incontrôlé
Prestations et aides sociales, le dérapage incontrôléPrestations et aides sociales, le dérapage incontrôlé
Prestations et aides sociales, le dérapage incontrôlé
 
Kata rules esp january 2013
Kata rules esp january  2013Kata rules esp january  2013
Kata rules esp january 2013
 
مختارات من النثر العربي اختارها ادونيس
مختارات من النثر العربي اختارها ادونيسمختارات من النثر العربي اختارها ادونيس
مختارات من النثر العربي اختارها ادونيس
 
تفسير العشر الأخير من القرآن الكريم ويليه أحكام تهم المسلم
 تفسير العشر الأخير من القرآن الكريم ويليه أحكام تهم المسلم  تفسير العشر الأخير من القرآن الكريم ويليه أحكام تهم المسلم
تفسير العشر الأخير من القرآن الكريم ويليه أحكام تهم المسلم
 
Tetsuro susumu's cartoon(2003 12) 2[1]
Tetsuro susumu's cartoon(2003 12) 2[1]Tetsuro susumu's cartoon(2003 12) 2[1]
Tetsuro susumu's cartoon(2003 12) 2[1]
 
Controlling globalweatheroct01
Controlling globalweatheroct01Controlling globalweatheroct01
Controlling globalweatheroct01
 
Web技術勉強会 第28回
Web技術勉強会 第28回Web技術勉強会 第28回
Web技術勉強会 第28回
 
Budhist values 5.chapter
Budhist values 5.chapter Budhist values 5.chapter
Budhist values 5.chapter
 
ديوان الشعر العربي الامارات وقطر وعمان
ديوان الشعر العربي الامارات وقطر وعمانديوان الشعر العربي الامارات وقطر وعمان
ديوان الشعر العربي الامارات وقطر وعمان
 
01-05-16-35
01-05-16-3501-05-16-35
01-05-16-35
 

More from Eric ShangKuan

Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計
Eric ShangKuan
 
透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps
Eric 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' View
Eric ShangKuan
 
Tuning Web Performance
Tuning Web PerformanceTuning Web Performance
Tuning Web Performance
Eric ShangKuan
 

More from Eric ShangKuan (16)

運用 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
 
Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計Internet Explorer 10: 重新想像網站設計
Internet Explorer 10: 重新想像網站設計
 
透過 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
 
Microsoft and jQuery
Microsoft and jQueryMicrosoft and jQuery
Microsoft and jQuery
 
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
 
An Introduction to GAEO web framework
An Introduction to GAEO web frameworkAn Introduction to GAEO web framework
An Introduction to GAEO web framework
 
Intro. to JavaScript
Intro. to JavaScriptIntro. to JavaScript
Intro. to JavaScript
 
Intro. to CSS
Intro. to CSSIntro. to CSS
Intro. to CSS
 
The Google App Engine Oil Framework
The Google App Engine Oil FrameworkThe Google App Engine Oil Framework
The Google App Engine Oil Framework
 

jQuery Tutorial

  • 1. jQuery Tutorial 上官林傑 (ericsk) 2008/07/25
  • 2. 課程大綱 JavaScript Framework jQuery 設計概念 jQuery 選擇器及 DOM 基本操作 事件處理及 Ajax 特效與 UI 實作練習
  • 3. quot; If I have seen further, it is by standing on the shoulders of Giants. quot; Issac Newton , 1676.
  • 4. Why JavaScript Framework? JavaScript 太難寫了! 有 framework 可以減輕負擔,何樂而不為? 各個瀏覽器各自為政 (其實也就 MSIE 比較不合群一點) 不要再浪費時間在處理跨瀏覽器的問題了。 站在巨人的肩膀上,讓專業的來 牛頓都跟你說了... 容易有範本可以抄 (好工程師不要學...) 嗯,免得東抄西抄 code 更難維護 ...
  • 5. Why jQuery? 好學好用,重點是它還很輕巧 以物件為中心,可以是主格也可以是受格。 e.g., 有 append 也可以 appendTo 完整的源碼大小(壓縮後傳輸)僅僅 16 Kb (版本1.2.6) 超棒超快速的選擇器 完全支援 CSS 3 及 XPath 選擇器,容易操作網頁上的物件。 一次呼叫便套用至所有被選擇到的元素。 Open Source & Google hosted 不用自己煩惱更換版本或是擺放 jQuery 的位址。 ...
  • 7. jQuery 能做的事... 新增或移除 DOM 物件(網頁上的元素) 更改網頁元素的樣式及內容 處理事件 產生特效或動畫 Ajax ....
  • 8. jQuery 的設計概念 jQuery 是用來操作選擇器的物件,也是整套 framework 的 prototype 所有東西都是 jQuery,也可以簡單寫作 $。 所有 API 的回傳值都是 jQuery 物件及陣列 jQuery 物件 -> 可以接 combo 技 e.g., $('<h1>test</h1>').css({color:'red'}).attr({id: 'title'}).appendTo($('body')); 陣列 -> 一個動作套用到全部 e.g., $('.items').addClass('selected');
  • 9. 使用 jQuery 1. 在 http://jquery.com/ 下載最新的 jquery*.js 檔案,然後跟你的 project 擺在一起並且引入。 e.g., <script type=quot;text/javascriptquot; src=quot;jquery-1.2.6.min. jsquot;></script> 2. 直接使用 Google host 的 jQuery <script type=quot;text/javascriptquot; src=quot;http://ajax. googleapis.com/ajax/libs/jquery/1/jquery.min.jsquot; ></script>
  • 10. jQuery Hello World $('<h1>Hello, world</h1>').appendTo($('body')); 作了什麼事? 1. 動態產生了一個 <h1>Hello, world</h1>,並且把它變成 jQuery 物件。 2. 使用 jQuery.appendTo API 將之插入到 body tag 的最後面。
  • 11. jQuery 選擇器 jQuery 的選擇器包括: 一段 HTML,如果沒有 match 到則會產生新的。 $('<div>test</div>') 標籤名 $('body') CSS 3 選擇器 $('ul > li.selected') XPath $('a[@href^=http://www.cht]')
  • 12. jQuery 選擇器(續) 搭配選擇器一同服用的 filter $('ul > li:even'), $('ul > li:first-child') 表單特殊的選擇器 $(':checked'), $(':input') 除了直接選擇之外,也可以加入 context: $('div', '#panel')
  • 13. jQuery 陣列 因為 jQuery 選擇後都是回傳「陣列」,所以可以用陣列長度是 否大於 0 來判斷是不是有選到東西: if ($('.checked').length == 0) { alert('您還沒有勾選'); } 針對每個選到的元素操作: 如果是 jQuery API,直接套用即可。 否則: $('.selected').each(function(index , domElem ) { .... });
  • 14. jQuery 陣列(續) 雖然回傳的都是 jQuery 物件,但可以用 get([index]) 取回 DOM Element。 $('#nick').get(0) == document.getElementById('nick') 也可以用 index() 來查該 DOM element/jQuery object 在 陣列中的位置。 1.2.3以前只能查 DOM element,後來我發了一個 ticket 請 jQuery team 支援查 jQuery object
  • 15. 讀取、修改元素 內容 使用 html() 或 text() 來塞一段或讀取 HTML code 或 text 在選到的元素。 沒帶參數是讀出來: var content = $('#test').html(); 加了參數是修改: $('#test').html('modified content'); 很多 jQuery 的 API 都有上述的設計(getter/setter)
  • 16. 讀取、修改元素 內容(續) <div id=quot;fooquot;>abcdefg</div> var c = $('#foo').html(); // c 的值為 quot;abcdefgquot; ... ... // 把 #foo 的內容改成 hij $('#foo').html('hij'); <div id=quot;fooquot;>hij</div>
  • 17. 元素屬性 用 attr() 來處理元素中的屬性 一樣有前述 getter/setter 的設計,不過參數可以帶字串或是 JSON object: // 取得 id 的 值 $(...).attr('id'); $(...).attr('id', 'foo'); // 將 id 改成 foo 一次設定多個屬性 $('.foo').attr({rel: 'bar', title: 'show me'}); <div class=quot;fooquot;>...</div> <div class=quot;fooquot;>...</div> <div class=quot;fooquot; rel=quot;barquot; title=quot;show mequot;>...</div> <div class=quot;fooquot; rel=quot;barquot; title=quot;show mequot;>...</div>
  • 18. 元素樣式 用 css() 修改樣式 效果如同直接修改 style 屬性,所以要用 style 的名稱 (backgroun-color -> backgroundColor) $('.foo').css({textAlign: 'center', color: 'red'}); <div class=quot;fooquot;>...</div> <div class=quot;fooquot; style=quot;text-align:center;color: red;quot;>...</div>
  • 19. 元素的 class 利用 addClass() 或 removeClass() 來新增移除 class 若是直接修改 class 屬性,要自行處理字串。 $('.foo').addClass('highlight'); <div class=quot;fooquot;>...</div> <div class=quot;foo highlightquot;>...</div> $('.foo').removeClass('foo'); <div class=quot;foo highlightquot;>...</div> <div class=quot;highlightquot;>...</div>
  • 20. DOM 操作 內部插入元素: append(), appendTo() -- 插入最後 prepend(), prependTo() -- 插入最前 $('.foo').append('<b>hello</b>'); $('<em>test</em>').prependTo($('#x')); <div id=quot;xquot;> <div class=quot;fooquot;> ... ... </div> </div> <div id=quot;xquot;> <div class=quot;fooquot;> <em>test</em> ... ... <b>hello</b> </div> </div>
  • 21. DOM 操作(續) 外部插入元素: wrap() $('.foo').wrap('<p id=quot;panelquot;>'); <div class=quot;fooquot;>...</div> <p id=quot;panelquot;> <div class=quot;fooquot;>...</div> </p>
  • 22. DOM 操作(續) 前後插入 before(), insertBefore() after(), insertAfter() $('.foo').after('<img src=quot;load.gifquot; alt=quot;loadingquot;/>'); <div class=quot;fooquot;>...</div> <div class=quot;fooquot;>...</div> <img src=quot;load.gifquot; alt=quot;loadingquot;/> 更多 jQuery DOM 操作請參考  http://docs.jquery.com/Manipulation
  • 23. DOM 走訪 (Traversing) 在選擇某元素後,再透過 traverse/filter 的 API 來「再選擇」其 它的元素。 前後一個 $(...).prev([filter] ); $(...).next([filter] ); $('.foo').next(); <div class=quot;fooquot;>...</div> <img src=quot;load.gifquot; alt=quot;loadingquot;/>
  • 24. DOM 走訪 (Traversing) 親子關係 $(...).parent([filter] ); $(...).children([filter] ); $(...).siblings([filter] ); 篩選器 $(...).eq(index ); $(...).filter([filter] ); 更多 DOM 走訪 操作請參考  http://docs.jquery.com/Traversing
  • 26. jQuery 的事件處理 jQuery Events API 除了可以用一致的方式註冊事件處理器之 外,也 統一了 event object 可以方便 trigger (自訂) 事件 可以暫時開關事件處理器 ... 類似其它 API 的 getter/setter 的方式,但是 傳入參數時,是傳入一個事件處理器 若沒傳參數,則是 trigger 該事件
  • 27. 註冊事件處理器 處理 click 事件: $(...).click(function(evt) { alert('clicked'); }); 或是 $(...).bind('click', function(evt) { alert('clicked'); });
  • 28. 事件處理器(續) 只做一次: $(...).one('click', funciton(e) { ... }); 移除處理器: $(...).unbind('click');
  • 30. 自訂事件 利用 bind 註冊自己的事件: $(...).bind('dlg-open', function(e) { .... }); 利用 trigger 來觸發 $(...).trigger('dlg-open'); 利用 unbind 來移除 $(...).unbind('dlg-open');
  • 31. onload shortcut 在整頁都讀取完才做事 處理 window.onload 的 event 在 jQuery 中可以直接寫: $(function() { .... }); 即表示該 function 會在整頁讀完之後才運作。
  • 32. AJAX
  • 33. jQuery AJAX API 專門用來處理 Ajax 的動作,可以直接使用 $.ajax() 來使用, 再依照需求修改參數。 有 $.get(), $.post(), $.load() 這些 shortcut 可以使用 會自動觸發 ajax**** 事件,其它元素可以註冊這些事件的處 理器。
  • 34. $.ajax $.ajax({ // 用來指定要 request 的 URL url: '/foo.php', // 是要用 GET/POST 的方式作 request type: 'post', // request 的資料 data: { ... }, // 回傳的資料型態,會影響 success callback 的參數 dataType: 'json', // 是否要 cache 住 response cache: false, // 在 ajax 發起 request 前呼叫 beforeSend: function() { .... }, // ajax 發生錯誤時呼叫 error: function(xhr) { ... }, // 成功完成 reuqest 時呼叫 success: function(resp) { ... }, // 最後呼叫 complete: function(xhr) { ... } });
  • 35. 範例:送出需求後更改某區域 內容 $.ajax({ url: 'foo.php', data: {x: 'abc', y: 123}, success: function(resp) { $('#bar').html(resp); } }); 或是 $('#bar').load('foo.php', {x: 'abc', y: 123});
  • 36. jQuery 自訂 ajax 事件 透過註冊這些事件的處理器,當 ajax 在進行時,會依照進行的 狀況驅動適當的事件 有 ajaxStart, ajaxSend, ajaxStop, ajaxError, ajaxSuccess, ajaxComplete 這些自訂的 ajax 事件。
  • 38. jQuery 預設的特效 預設在 jQuery 的函式庫中提供了基本常見的特效: 顯示或消失(show、hide) 向上或向下捲動(slideUp、slideDown) 淡入或淡出(fadeIn、fadeOut、fadeTo) 也可以自己設計特效。 使用 animates()
  • 39. jQuery UI http://ui.jquery.com/ 另外一組團隊基於 jQuery 所設計的 UI widget,網站上可以客 製化需求下載 javascript 檔案來使用。 也可以到 jQuery UI theme roller 網站選擇或設計自己的 theme (CSS) 來改善 UI 美觀。 http://ui.jquery.com/themeroller
  • 41. 寫 jQuery plugin 好處:重覆利用自己的 code,分享給團隊開發者一起使用。 方法: 定義在 $.fn 下 符合 jQuery-style 來寫作 API 要套用到「所有」被選擇到的元素。 記得傳回 jQuery 陣列。 注意儘量不要寫出會產生衝突的 code 避免定義容易重覆的名稱。 從別人的 code 中學習 http://plugins.jquery.com/
  • 42. 套用至「所有」被選擇到的元素 利用 $.each $.fn.foo = function({ return this.each(function() { // TODO: 你要做的事 }); });
  • 43. 包裝 plugin 避免寫出與其它 js 檔案相衝 code (function($){ .... })(jQuery); 如果能用 JSMin 或 YUI Compressor 壓縮一下也不錯。
  • 45. 請愛用 jQuery 讓 JavaScript 變好寫了(咦?) 解決了不少跨瀏覽器間的問題。 用了公認好用的 framework,在維護上也比較輕鬆。 code 小、速度快。 ...
  • 46. 線上資源 官方網站 :  http://jquery.com/ 專案網站 :  http://code.google.com/p/jqueryjs/ jQuery UI: http://ui.jquery.com/ 中文 jQuery 討論群組: http://groups.google.com/group/jquery-