Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Speaker Deck
PRO
Sign in
Sign up
for free
jQuery 入門
Ping-Yen Tsai
May 06, 2013
Technology
0
42
jQuery 入門
Ping-Yen Tsai
May 06, 2013
Tweet
Share
More Decks by Ping-Yen Tsai
See All by Ping-Yen Tsai
pingyen
0
33
pingyen
2
340
pingyen
0
57
pingyen
1
56
pingyen
0
30
pingyen
0
42
pingyen
0
210
pingyen
0
60
pingyen
0
45
Other Decks in Technology
See All in Technology
yunoda
0
120
kawaguti
2
410
viva_tweet_x
3
2.7k
hashhub
3
16k
oliva
7
1.1k
binarymist
0
1.3k
masakazu
0
130
gobeyond20xx
0
170
iwashi86
53
23k
myajiri
0
310
hayatan
0
190
buildersbox
0
200
Featured
See All Featured
dotmariusz
94
5.5k
paulrobertlloyd
72
1.4k
tanoku
86
8.6k
geoffreycrofte
21
920
eitanlees
112
10k
zakiwarfel
88
3.4k
holman
288
130k
jmmastey
10
610
jensimmons
207
10k
jakevdp
775
200k
robhawkes
52
2.8k
qrush
285
19k
Transcript
jQuery ⼊入⾨門 蔡秉諺 1
課前準備 • jQuery 官網 • http://jquery.com/ • http://api.jquery.com/ • 安裝
Chrome • https://www.google.com/chrome • 安裝 Notepad++ • http://notepad-plus-plus.org/
Chrome JavaScript 控制台 • 開啟 • 右上選單按鈕 -> ⼯工具 ->
JavaScript 控制台 • 滑⿏鼠右鍵 -> 檢查元素 -> 左下 Show Console • 玩 > 1 + 1 2 > var a = 1; undefined > a 1 > alert(a); undefined > window Window 下⼀一⾏行顯⽰示的是什麼? 就好像在程式碼前加上 var x = 變成 var x = 1 + 1 然後把 x 的值顯⽰示在下⼀一⾏行
None
jQuery • 語法⽐比 JavaScript 好懂 • 處理瀏覽器差異 • 處理瀏覽器 Bug
JavaScript var divs = document.getElementByTagName('div'), n = divs.length; for(i =
0; i < n; ++i) divs[i].style.display = 'none'; jQuery $('div').hide();
JavaScript var req; if(window.XMLHttpRequest) req = new XMLHttpRequest(); else req
= new ActiveXObject('Microsoft.XMLHTTP'); req.onreadystatechange = function() { if(req.readyState !== 4 || req.status !== 200) return; var data = eval('(' + req.responseText + ')'); alert(data.ID); } req.open('GET', 'demo.php', true); req.send(); jQuery $.getJSON('demo.php', function(data) { alert(data.ID); });
JavaScript var btn = document.getElementById('btn1'); if(btn.addEventListener) btn.addEventListener('click', handler, false); else
btn.attachEvent('on' + event, handler); function handler() { alert('Clicked!'); } jQuery $('#btn1').click(function() { alert('Clicked!'); });
讓網⾴頁執⾏行 jQuery <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head>
<body> <script> alert(jQuery); // function() { ... } alert($); // function() { ... } alert(jQuery === $); // true </script> </body> </html> 在網⾴頁嵌⼊入 jQuery 程式碼 var jQuery = function() { /* 略 */ } var $ = jQuery; /* 替 jQuery 函式增加其他屬性 */ 多 jQuery 和 $ 兩個⼀一模⼀一樣的變數
jQuery 程式碼哪裡來 • http://jquery.com/download/ • 壓縮版 & 未壓縮版 • 產品使⽤用
& 開發使⽤用 • CDN • Microsoft • Google • jQuery 官⽅方 ( MediaTemple ) • The best CDN for jQuery in 2012
讓網⾴頁執⾏行 jQuery • 下載 jQuery 程式碼 • 將檔名 jquery-1.9.1.js 改為
jquery.js • 開啟 Notepad++ • 新增右側內容 • 儲存為 demo.html • ⽤用 Chrome 開啟 • 玩 JavaScript 控制台 • 玩開發⼈人員⼯工具 <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <script> alert(jQuery); // function() { ... } alert($); // function() { ... } alert(jQuery === $); // true </script> </body> </html>
找東⻄西 & 做事情 $('div').html('<b>DEMO</b>'); 找東⻄西 做事情 <!DOCTYPE html> <html> <head>
<script src="jquery.js" ></script> </head> <body> <div></div> <div></div> <div></div> <script> $('div').html('<b>DEMO</b>'); </script> </body> </html> 找出所有的 DIV 塞⼊入 <b>DEMO</b>
找東⻄西 • ⽤用 CSS Selector 找 • ⽀支援 CSS3 Selector
<!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div class="class1" id="id1" ></div> <div class="class1" ></div> <div class="class2" ></div> <div class="class1 class2" ></div> <script> $('div').html('A'); $('#id1').html('B'); $('.class1').html('C'); $('.class1.class2').html('D'); </script> </body> </html> 同時具有 class1 class2 HTML 空⽩白間隔 CSS 無空⽩白間隔 CSS 空⽩白間格另有意義
找東⻄西 • ⽤用 CSS Selector 找 • ⽀支援 CSS3 Selector
<!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div id="id1" ><span><i></i></span></div> <div><span></span></div> <script> $('div span').html('A'); $('#id1 i').html('B'); $('#id1 > i').html('C'); $('#id1 > span > i').html('D'); </script> </body> </html>
找東⻄西 <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body>
<form> <input type="text" /> <input type="text" class="class1" /> <input type="submit" value="submit" /> </form> <script> $('input[type=text]').val('abc'); $('.class1[type=text]').val('xyz'); </script> </body> </html> • ⽤用 CSS Selector 找 • ⽀支援 CSS3 Selector
找東⻄西 • CSS3 Selector ⽂文件 • W3Schools CSS Selector Reference
• div+p • a[href^="https"] • a[href$=".pdf"] • a[href*="w3schools"] • input:checked • jQuery Selector Extensions • 不屬於 CSS3 Selector ,只有 jQuery 有 注意 W3Schools 寫 a[src^="https"] 是嚴重錯誤
找東⻄西 • K ⽂文件、看範例、玩 ! • Chrome JavaScript 控制台 •
Xuite
找東⻄西 <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body>
<div><i></i></div> <div><span><i></i></span></div> <script> </script> </body> </html> $('div i').html('A'); $('div > i').html('B'); $('div > span > i').html('C'); $('div').find('i').html('A'); $('div').children('i').html('B'); $('div').children('span').children('i').html('C'); 意義相同 效能較佳
找東⻄西 • jQuery API Traversing • .find() • .children() •
.eq() • .parent() • .parents() • .next() • .prev() • … <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div></div> <div></div> <div></div> <script> $('div').eq(1).html('ABC'); </script> </body> </html> 第⼆二個 DIV 由 0 起算
找東⻄西 • K ⽂文件、看範例、玩 ! • Chrome JavaScript 控制台 •
Xuite
做事情 $('div').html('<b>DEMO</b>'); 找東⻄西 做事情 塞⼊入 <b>DEMO</b>
做事情 • jQuery API • Attributes • CSS • Effects
• Manipulation • Events • Data • …
做事情 • 同⼀一個 method 可以做很多事情 • $('div').html(); • $('div').html('ABC'); •
$('div').html(function() { return Date(); });
做事情 • 取值 • 取找東⻄西中第⼀一個的值 <!DOCTYPE html> <html> <head> <script
src="jquery.js" ></script> </head> <body> <div>1</div> <div>2</div> <div>3</div> <script> alert($('div').html()); // 1 </script> </body> </html>
做事情 • 設定值 • 設定所有找東⻄西的值 <!DOCTYPE html> <html> <head> <script
src="jquery.js" ></script> </head> <body> <div>1</div> <div>2</div> <div>3</div> <script> $('div').html('ABC'); $('div').html(function() { return Date(); }); </script> </body> </html> 只設定第⼀一個 DIV 的 HTML $('div').eq(0).html('XYZ');
Attributes • .val() • HTML 元素 value <!DOCTYPE html> <html>
<head> <script src="jquery.js" ></script> </head> <body> <form> <input type="text" value="demo" /> <input type="submit" value="submit" /> </form> <script> alert($('input').val()); // demo $('input').val('ABC'); </script> </body> </html> 第⼀一個 INPUT 所有 INPUT
Attributes • addClass() • removeClass() • toggleClass() • hasClass() <!DOCTYPE
html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div class="class1" ></div> <div class="class2 class3" ></div> <div class="class1 class2" ></div> <script> $('div').addClass('class4'); $('div').removeClass('class1'); $('div').toggleClass('class2'); alert($('div').hasClass('class3')); // true </script> </body> </html> 沒的加上 有的拿掉 其中⼀一個 DIV 有就跳 true
Attributes • .prop() • .removeProp() • 無法移除原⽣生屬性 <!DOCTYPE html> <html>
<head> <script src="jquery.js" ></script> </head> <body> <a title="1" href="1.html" >1</a> <a title="2" href="2.html" >2</a> <script> alert($('a').prop('title')); // 1 $('a').prop('title', 'ABC'); $('a').prop('title', null); $('a').prop({ 'title' : 'XYZ', 'href' : 'demo.html' }); </script> </body> </html> 第⼀一個 A 傳⼊入 JavaScript 物件 ⼀一次改多個 DOM Property $('a').removeProp('title'); 運作異常
Attributes • .attr() • ⼤大致對應 DOM getAttribute() setAttribute() • .removeAttr()
• ⼤大致對應 DOM removeAttribute() • 歷史共業 • jQuery 先有 .attr() 才有 .prop() • 新版多⽤用 .prop() • JavaScript property 、 DOM property 、 HTML attribute
CSS • .css() <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script>
</head> <body> <div id="id1" >1</div> <div id="id2" >2</div> <script> $('#id1').css('font-size', '36px'); alert($('div').css('font-size')); // 36px $('#id2').css({ 'background-color' : '#0F0', 'font-size' : '24px' }); </script> </body> </html> 第⼀一個 DIV 傳⼊入 JavaScript 物件 ⼀一次改多個 CSS 屬性
CSS • .height() • ⾼高 • .innerHeight() • ⾼高 +
padding • .outerHeight() • ⾼高 + padding + border (+ margin)
CSS • .width() • 寬 • .innerWidth() • 寬 +
padding • .outerWidth() • 寬 + padding + border (+ margin)
CSS • .offset() • 相對網⾴頁 • .position() • 相對 offsetParent
<!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div id="parent" style="position : absolute; top : 100px; left : 100px" > <div id="child" style="position : absolute; top : 50px; left : 50px" > DEMO </div> </div> <script> console.log($('#child').offset()); // 150, 150 console.log($('#child').position()); // 50, 50 </script> </body> </html> 回傳⼀一物件,有 top 、 left 兩屬性
CSS • .scrollLeft() • 橫向捲軸 • .scrollTop() • 縱向捲軸
Effects • .hide() • CSS display : none • .show()
• .toggle() <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div id="id1" >1</div> <div id="id2" >2</div> <div id="id3" >3</div> <div id="id4" >4</div> <script> $('#id1').hide(); $('#id2').hide(function() { alert('ABC'); }); $('#id3').hide('slow'); $('#id4').hide(800, function() { alert('XYZ'); }); </script> </body> </html> Callback 總是最後⼀一個參數
Effects • .fadeOut() • .fadeIn() • .fadeToggle()
Effects • .slideUp() • .slideDown() • .slideToggle()
Effects • .animate() • 客製動畫
串 • 找東⻄西 • 回傳 jQuery 物件 • 做事情 •
取值 • 回傳值 • 設定值 • 回傳 jQuery 物件 <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div id="id1" > <div></div> <div></div> </div> <script> $('#id1').children('div') .html('<a href="demo.html" >DEMO</>') .css({ 'background' : '#F00', 'padding' : '20px'}) .children('a') .fadeOut() .fadeIn(); </script> </body> </html> 這裡開始對象變 #id1 > div > a
找東⻄西、做事情、串 • K ⽂文件、看範例、玩 ! • Chrome JavaScript 控制台 •
Xuite
Manipulation • .append() 與 .appendTo()<!DOCTYPE html> <html> <head> <script src="jquery.js"
></script> </head> <body> <div id="id1" ></div> <script> $('<a href="demo.html" >DEMO</a>').appendTo('#id1'); $('#id1').append('<a href="demo.html" >DEMO</a>'); </ script> </body> </html> 傳⼊入 CSS Selector DOM 物件 HTML 都可以 功能相同 作⽤用對象不同
Manipulation • .append() 與 .appendTo() • .prepend() 與 .prependTo() •
.after() 與 .insertAfter() • .before() 與 .insertBefore()
Manipulation • .empty() • 清空⼦子節點 • .remove() • 移除⾃自⼰己
Manipulation • .wrap() • .wrapInner() • .wrapAll() • .unwrap()
Manipulation • K ⽂文件、看範例、玩 ! • Chrome JavaScript 控制台 •
Xuite • 記得串 !
Events • .bind() • .unbind() <!DOCTYPE html> <html> <head> <script
src="jquery.js" ></script> </head> <body> <div id="id1" >1</div> <div id="id2" >2</div> <script> $('#id1').bind('click', function() { alert('!'); }); function f() { alert('!!'); } $('#id2').bind('click', f); $('#id2').unbind('click', f); </script> </body> </html>
Events • .click() • .bind('click', function() { /* … */
}) 的縮寫 <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div>DEMO</div> <script> $('div').click(function() { alert('!'); }); </script> </body> </html> 與 $('div').bind('click', function() { alert('!'); }); 意義相同
Events • .blur() • .change() • .click() • .dblclick() •
.focus() • .keydown() • .keypress() • .keyup() • .load() • .mousedown() • .mousemove() • .mouseout() • .mouseover() • .mouseup() • .resize() • .scroll() • .submit() • .unload() • …
Events • .one() • 只執⾏行⼀一次 <!DOCTYPE html> <html> <head> <script
src="jquery.js" ></script> </head> <body> <div>DEMO</div> <script> $('div').one('click', function() { alert('!'); }); </script> </body> </html>
Events • .on() • .off() <!DOCTYPE html> <html> <head> <script
src="jquery.js" ></script> </head> <body> <div><span>DEMO</span></div> <script> $('div span').click(function() { alert('!'); }); $('div').on('click', 'span', function() { alert('!!'); }); $('div').append('<span>DEMO2</span>'); </script> </body> </html> 按 DEMO 會跳 ! 和 !! 按 DEMO2 只會跳 !!
Events • $(document).ready(function() { /* ... */ }) • DOMContentLoaded
• DOM Tree 建⽴立完成時,圖⽚片、CSS 載⼊入完成前 • ⽐比 $(window).load(function() { /* ... */ }) 早 • 縮寫 $(function() { /* ... */ })
Data • .data() • 在 jQuery 物件上儲存資料 • .removeData() <!DOCTYPE
html> <html> <head> <script src="jquery.js" ></script> </head> <body> <div>DEMO</div> <script> $('div').data('key', '1qaz2wsx'); $('div').click(function() { alert($(this).data('key')); // 1qaz2wsx }); </script> </body> </html>
jQuery 物件當 Array ⽤用 • $('div').length • 有多少個 DIV •
$('div')[2] • 第三個 DIV 的 DOM 物件 第三個 DIV 的 jQuery 物件 $('div').eq(2)
.each() <!DOCTYPE html> <html> <head> <script src="jquery.js" ></script> </head> <body>
<div></div> <div></div> <div></div> <div></div> <div></div> <script> $('div').each(function(index) { $(this).html(index); }); </script> </body> </html>
Events 、 Data 、 當 Array 、 .each() • K
⽂文件、看範例、玩 ! • Chrome JavaScript 控制台 • Xuite • 寫新網⾴頁 • 記得串 !
jQuery 函式的屬性 var jQuery = function() { this.addClass = function()
{ /* 略 */ return this; } /* 略 */ return this; } var $ = jQuery; jQuery.get = function() { /* 略 */ } jQuery.post = function() { /* 略 */ } /* 略 */ jQuery 函式的屬性 類似 Java 的 Static ⽅方法
Ajax • $.get() • jQuery 函式的屬性 • HTTP GET $.get('data.php',
function(data) { console.log(data); });
Ajax • $.post() • jQuery 函式的屬性 • HTTP POST $.post('target.php',
function(data) { console.log(data); }); $.post('target.php', { name : "John", time : "2pm" }, function(data) { console.log(data); });
Ajax • $.getJSON • HTTP GET • ⾃自動將 JSON 轉為
JavaScript 物件 • ⽀支援 JSONP • 網址加上 callback=? $.getJSON('https://graph.facebook.com/pingyen.tsai?callback=?', function(data) { alert(data.name); });
Ajax • $.ajax() • 客製化 Ajax • settings • cache
• crossDomain • dataType • … $.ajax({ url : 'https://graph.facebook.com/pingyen.tsai', crossDomain : true, success : function(data) { alert(data.name); }}); Cross-Domain 要瀏覽器與伺服器同時⽀支援
Ajax • K ⽂文件、看範例、玩 ! • ⽤用 $.getJSON() 抓⾃自⼰己的 Facebook
資料 • ⽤用 $.ajax() 抓⾃自⼰己的 Facebook 資料
Deferred Object • $.get('a.php') -> $.get('b.php') -> $.get('c.php') $.get('a.php', function(data)
{ $.get('b.php', function(data) { $.get('c.php', function(data) { // ... }); }); }); $.get('a.php') .then(function(data) { return $.get('b.php'); }) .then(function(data) { return $.get('c.php'); }) .done(function(data) { // ... }); 傳統寫法 新寫法
Deferred Object • $.get('a.php') $.get('b.php') $.get('c.php') 同時 • 三者皆完成進⾏行下⼀一步 傳統寫法
~!@#$%^&* $.when($.get('a.php'), $.get('b.php'), $.get('c.php')) .done(function(arr, arr2, arr3) { // ... }); 新寫法
Deferred Object • 視情況 $.get('a.php') 或 $.get('b.php') if(type === 'A')
$.get('a.php', function(data) { f(data.a); }); else $.get('b.php', function(data) { f(data.b); }); function f(p) { // ... } 傳統寫法 var d; if(type === 'A') d = $.get('a.php') .then(function(data) { return data.a; }); else d = $.get('b.php') .then(function(data) { return data.b; }); d.done(function(p) { // ... }); 新寫法 由 上 到 下
Deferred Object • 有值直接⽤用 沒值 $.get('a.php') if(localStorage.x) f(localStorage.x); else $.get('a.php',
function(data) { var x = data.x; localStorage.x = x; f(x); }); function f(p) { // ... } 傳統寫法 var d; if(localStorage.x) d = $.when(localStorage.x); else d = $.get('a.php') .then(function(data) { var x = data.x; localStorage.x = x; return x; }); d.done(function(p) { // ... }); 新寫法 由 上 到 下
jQuery 1.9 vs. jQuery 2.0 • API ⼀一模⼀一樣 • 但
jQuery 2.0 不⽀支援 IE 6 7 8 • 更輕量 <!--[if lt IE 9]> <script src="jquery-1.9.js"></script> <![endif]--> <!--[if gte IE 9]><!--> <script src="jquery-2.0.js"></script> <!--[endif]-->
jQuery Plugins • http://plugins.jquery.com/ • jQuery Cookie • Google 搜尋
jQuery Plugin
jQuery UI • http://jqueryui.com/
網路資源 • http://try.jquery.com/ • http://jsfiddle.net/ • http://www.bibeault.org/jqia2/ • https://tutsplus.com/course/30-days-to-learn-jquery/
Deferred Object 、 jQuery UI • K ⽂文件、看範例、玩 ! •
⽤用 $.getJSON() + Deferred 抓好友們的 Facebook 資料 • ⽤用 $.ajax() + Deferred 抓好友們的 Facebook 資料