jQuery教學 - 常用函式
1. 核心(Core)
1.1 $(something)
依據參數產生或取得jQuery物件
- $(selector)
依據selector規則取得Elements,例如
$('#my-element')
- $(element)
將原生的DOM物件轉為jQuery物件,例如
var element = document.getElementById('my-element'); element = $(element);
- $(html)
建立Element,例如
$('<div>Test</div>');
1.2 選擇器(Selectors)
jQuery除了可以利用CSS選擇器的規則找到網頁元素,還可以用其他特別的規則選取,這邊只介紹最常用的標準CSS選擇器規則。
1.2-1 ID選擇器(ID Selector)
使用井號(#)開頭。
$('#my-id')
對應到HTML
<div id="my-id">This is id selector.</div>
1.2-2 類別選擇器(Class Selector)
使用點(.)開頭。
$('.my-class')
對應到HTML
<div class="my-class">This is class selector.</div>
1.2-3 型態選擇器(Type Selector)
使用HTML的標籤
$('div')
對應到HTML
<div>This is type selector.</div>
1.2-4 後代選擇器(Descendant selectors)
使用空白表示階層關係
$('.my-class div')
對應到HTML
<div class="my-class"> <div>This is descendant selector.</div> </div>
將取得內部的DIV元素
1.2-5 屬性選擇器(Attribute Selector)
使用中括號包夾
$('[type=text]')
對應到HTML
<input type="text" />
1.2-6 OR
使用逗號(,)隔開
$('#my-id, .my-class')
對應到HTML
<div id="my-id">This is id selector.</div> <div class="my-class">This is class selector.</div>
1.2-7 AND
接多個選擇器連接在一起即表示要網頁元素須同時滿足所有規格
$('.my-class.my-class2')
對應到HTML
<div class="my-class my-class2">This is class selector.</div>
型態應該寫在最前面
$('div.my-class.my-class2')
2. 歷遍(Traversal)
.find(selector)
尋找Elements下的Elements,以下範例使用此HTML,紅色框線為選取的結果:
$('#body').find('h1.red');
.filter(selector)
從目前的結果過濾Elements
$('#body h1');
$('#body h1').filter('.red');
.children([selector])
取得Element下的子Elements
$('#body').children();
$('#body').children('.red');
.first()
取得目前結果的第一個Element
$('#body').children().first();
.last()
取得目前結果的最後一個Element
$('#body').children().last();
.eq(index)
從目前結果取得指定位置的元素
$('#body').children().eq(1);
.parent([selector])
取得父Element
$('#body div h1').parent();
$('#body div h1').parent('#body');
.parents([selector])
取得所有祖先Elements
$('#body div h1').parents();
$('#body div h1').parents('#body');
.closet(selector)
取得包含自己與祖先Elements中,最先符合條件的Element
$('#body div h1').closet('div');
$('#body div h1').closet('h1');
.has(selector)
過濾出目前結果中,子Elements中有符合選擇器的項目
$('div').has('div');
.each(handler)
將目前結果逐一送至Handler函式執行處理
$('li').each(function(index, element) { // do something // $(this) is also element });
.map(handler)
將目前結果逐一送至Handler函式執行處理,並回傳陣列結果
var ids = $('li').map(function(index, element) { return $('li').attr('id'); });
3. CSS
.hasClass(className)
判斷是否有class
<li class="active">Item</li>
element.hasClass('active'); // true
.addClass(className)
加入class
element.addClass('active');
<li>Item</li> => <li class="active">Item</li>
.removeClass(className)
移除class
element.removeClass('active');
<li class="active">Item</li> => <li>Item</li>
.toggleClass(className)
加入或移除class
element.toggleClass('active');
<li>Item</li> <=> <li class="active">Item</li>
.css(propertyName)
.css(propertyName, value)
取得或設定css style
var color = element.css('color'); element.css('color', 'red');
<li>Item</li> => <li style="color:red">Item</li>
也可以多筆設定
element.css({ 'color': 'red', 'background-color': 'green' });
<li>Item</li> => <li style="color:red;background-color:green">Item</li>
.width()
.width(value)
取得或設定寬度
var width = element.width(); element.width(100);
<li>Item</li> => <li style="width:100px">Item</li>
.height()
.height(value)
取得或設定高度
var height = element.height(); element.height(100);
<li>Item</li> => <li style="height:100px">Item</li>
4. 效果(Effects)
.show()
.hide()
顯示或隱藏Element
element.hide();
<li>Item</li> => <li style="display:none">Item</li>
element.show();
<li style="display:none">Item</li> => <li style="display:block">Item</li>
.fadeIn([duration] [, complete])
.fadeOut([duration] [, complete])
淡入或淡出Element
element.fadeIn(1000); element.fadeOut(1000, function() { $(this).remove(); });
5. 屬性(Attributes)
.attr(attributeName)
.attr(attributeName, value)
取得或設定屬性
var id = element.attr('id'); element.attr('id', 'myid');
<li>Item</li> => <li id="myid">Item</li>
.removeAttr(attributeName)
移除屬性
element.removeAttr('id');
<li id="myid">Item</li> => <li>Item</li>
6. 操作(Manipulation)
.text()
.text(value)
取得或設定文字內容
var text = element.text(); element.text('<b>Html tag will not work.</b>');
<li>Item</li> => <li><b>Html tag will not work.</b></li>
.html()
.html(value)
取得或設定HTML內容
var html = element.html(); element.html('<b>Html tag will work.</b>');
<li>Item</li> => <li><b>Html tag will work.</b></li>
.val()
.val(value)
取得或設定表單元件值
var val = element.val(); element.val('username');
<input type="text" /> => <input type="text" value="username" />
.append(element)
.appendTo(parentElement)
加入Element在最後面,以下範例使用此HTML
<div id="wrapper"> <div class="inner">A</div> <div class="inner">B</div> </div>
$('#wrapper').append('<div>C</div>'); $('<div>C</div>').appendTo('#wrapper');
結果
<div id="wrapper"> <div class="inner">A</div> <div class="inner">B</div> <div>C</div> </div>
prepend(element)
.prependTo(parentElement)
加入Element在最前面
$('#wrapper').prepend('<div>C</div>'); $('<div>C</div>').prependTo('#wrapper');
結果
<div id="wrapper"> <div>C</div> <div class="inner">A</div> <div class="inner">B</div> </div>
.after(element)
.insertAfter(siblingElement)
插入Element到後面
$('.inner').after('<div>C</div>'); $('<div>C</div>').insertAfter('.inner');
結果
<div id="wrapper"> <div class="inner">A</div> <div>C</div> <div class="inner">B</div> <div>C</div> </div>
.before(element)
.insertBefore(siblingElement)
插入Element到前面
$('.inner').before('<div>C</div>'); $('<div>C</div>').insertBefore('.inner');
結果
<div id="wrapper"> <div>C</div> <div class="inner">A</div> <div>C</div> <div class="inner">B</div> </div>
.replaceWith(element)
.replaceAll(targetElement)
取代Element
$('.inner').replaceWith('<div>C</div>'); $('<div>C</div>').replaceAll('.inner');
結果
<div id="wrapper"> <div>C</div> <div>C</div> </div>
.wrap(element)
包住Element
$('.inner').wrap('<div></div>');
結果
<div id="wrapper"> <div> <div class="inner">A</div> </div> <div> <div class="inner">B</div> </div> </div>
.wrapInner(element)
包住Element內容物
$('.inner').wrapInner('<div></div>');
結果
<div id="wrapper"> <div class="inner"> <div>A</div> </div> <div class="inner"> <div>B</div> </div> </div>
.wrapAll(element)
包住所有Elements
$('.inner').wrapAll ('<div></div>');
結果
<div id="wrapper"> <div> <div class="inner">A</div> <div class="inner">B</div> </div> </div>
.unwrap()
移除外層Element
$('.inner').unwrap();
結果
<div class="inner">A</div> <div class="inner">B</div>
.remove()
移除Element
$('.inner').remove();
結果
<div id="wrapper"> </div>
.clone()
複製Element
$('.inner').clone();
7. 事件(Events)
.ready(handler)
綁定載入完成之事件,通常用於綁定整個網頁載入的事件
$(document).ready(function() { // ... }); // 等於 $(function() { // ... });
.bind(eventType, handler)
綁定事件
$('.btn').bind('click', clickFunction);
.unbind([eventType] [, handler])
移除事件綁定
$('.btn').unbind('click', clickFunction); // 移除特定Handler $('.btn').unbind('click'); // 移除所有click事件的Handler $('.btn').unbind(); // 移除所有事件
.on(eventType [, selector], handler)
綁定事件,可透過選擇器使用事件代理(delegate)
$('.btn').on('click', clickFunction); // 與bind相同 $('body').on('click', '.btn', clickFunction); // 代理
.off([eventType] [, selector] [, handler])
移除事件,可移除代理事件
$('.btn').off('click', clickFunction); // 與unbind相同 $('.btn').off('click'); // 與unbind相同 $('.btn').off(); // 與unbinde相同 $('body').off('click', '.btn', clickFunction); // 移除特定代理事件 $('body').off('click', '.btn'); //移除在.btn上的click代理事件 $('body').off('click', '**'); //移除所有click代理事件
.trigger(eventType)
觸發事件
$('.btn').trigger('click');
.click([handler])
綁定或觸發Click事件
$('.btn').click(clickFunction); // 相當於 $('.btn').bind('click', clickFunction);
$('.btn').click(); // 相當於 $('.btn').trigger('click’);
其他和click類似用法的事件函數
.change()
.submit()
.mousedown()
.mouseup()
.mousemove()
.mouseover()
.mouseout()
…
8. AJAX
$.ajax(settings)
執行一個AJAX HTTP Reqeust
Settings
- url: 呼叫的URL
- type: HTTP Method, 例如: GET或POST, 預設為GET
- data: 要傳送的參數資料
- dataType: Server回傳的資料型態, 例如: xml, json, script, or html, 預設是自動判斷
- async: 預設是非同步傳送, 設成false可使用同步傳送
- cache: 設為false將強制不使用cache資料, 預設為true, dataType為script則為false
- success: 成功時執行
- error: 失敗時執行
- complete: 無論成功或失敗最後都執行
範例
$.ajax({ url: 'example.aspx', type: 'GET', data: { param1: 'value1' }, dataType: 'json', async: true, cache: true, success: function(data, textStatus, jqXHR) { }, error: function(jqXHR, textStatus, errorThrown) { }, complete: function(jqXHR, textStatus) { } })
結果會呼叫
GET example.aspx?param1=value1
如果cache設定為false則會呼叫
GET example.aspx?param1=value1&_=1407919336091
$.get( url [, data ] [, success ] [, dataType])
執行一個AJAX HTTP GET Request
$.get('example.aspx', params, 'json', successCallback); // 相當於 $.ajax({ url: 'example.aspx', type: 'GET', data: params, dataType: 'json', success: successCallback });
$.post( url [, data ] [, success ] [, dataType])
執行一個AJAX HTTP POST Request
$.post('example.aspx', params, 'json', successCallback); // 相當於 $.ajax({ url: 'example.aspx', type: 'POST', data: params, dataType: 'json', success: successCallback });
9. 其他
.get(index)
取得原生的DOM物件
$('#body').get(0).id // body
$.extend(target [, object1 ] [, objectN …])
合併多個object屬性到第一個object
$.extend({ option: 'default' }, userOptions);
$.isFunction(obj)
判斷一個物件是否為函式
$.isArray(obj)
判斷一個物件是否為陣列
$.isNumeric(obj)
判斷一個物件是否為數字
$.inArray(value, array)
搜索一個數值在陣列中的索引位置, 找不到就回傳-1
// 使用完全相等比對 $.inArray(10, ["8", "9", "10"]); // -1