這是學習 jQuery 期間整理的筆記,目的是快速回顧各 API 的用法,並練習思考「同樣的效果如何用原生 JavaScript 實作」。搭配閱讀早期 jQuery 原始碼、與其他框架對照優缺點,對理解底層很有幫助。
$().action // 選取元素後執行操作
$(function() { /* jQuery method */ }) // 等待文件載入完成
$(document).ready(function() { /* ... */ })
$("selector")、$("#id")、$(".class")。
click、dblclick、mouseenter、mouseleave、mousedown、mouseup、hover、focus、blur。
hide() / show() / toggle() $(selector).toggle(speed, callback);
fadeIn、fadeOut、fadeToggle、fadeTo(不透明度介於 0 到 1 之間)。
slideDown、slideUp、slideToggle。
$(selector).animate({params}, speed, callback);
params 為必填,幾乎可操作所有 CSS 屬性,但必須使用駝峰命名法;speed 可選(fast、normal、slow 或毫秒);callback 在動畫完成後執行。
停止動畫:
$(selector).stop(stopAll, goToEnd);
stopAll 是否清除整個動畫佇列,預設 false(僅停止目前動畫);goToEnd 是否立即跳到最終狀態,預設 false。
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
在同一組元素上一條接一條串接指令,是 jQuery 最迷人的語法特性之一。
取得:text()、html()、val()、attr()。
設定:text("text")、html("html")、val("value")、attr("name","value")。
這四個方法的設定形式都接受回呼函式,函式有兩個參數:目前元素在集合中的索引,以及原始(舊)值;回傳值即為新值。
新增:append、prepend、before、after。
刪除:remove() 移除元素及其子元素;empty() 只清空子元素;remove(".class") 可加上過濾條件。
addClass、removeClass、toggleClass。
$(selector).css("propertyname");
$(selector).css("propertyname","value");
$(selector).css({"propertyname":"value", "propertyname":"value"});
width、height、innerWidth、innerHeight、outerWidth、outerHeight。差別在於是否計入 padding 與 border。
祖先:parent、parents("selector")、parentsUntil("selector")。
後代:children()(可寫 $(div).children("p.1"))、find("selector")。
同胞:siblings、next、nextAll、nextUntil、prev、prevAll、prevUntil。
過濾:first、last、eq(0)、filter、not。
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if (statusTxt == "success") alert("載入成功");
if (statusTxt == "error") alert("錯誤:" + xhr.status + " " + xhr.statusText);
});
});
另外還有 $.get() 與 $.post() 兩個簡化方法。
var jq = $.noConflict(); 用於避免與其他函式庫的 $ 衝突;JSONP 則用於跨域資料請求。