把 jQuery 的特性拆成七個面向來看,會比零散記 API 清楚得多。以下每一項都附上可直接複製使用的程式碼。
$('#element'); // 等同 document.getElementById
$('.element'); // 依 class
$('p'); // 依標籤
$("form > input"); // 直接子元素
$("div,span,p.myClass"); // 一次選多種
$("tr:odd").css("background-color", "#bbbbff"); // 表格隔行上色
$(":input"); // 所有表單元素
$("input[name='newsletter']"); // 依 name 選特定表單元素
element.function(parameters);
$("p.surprise").addClass("ohmy").show("slow");
鏈式呼叫是 jQuery 最鮮明的風格:每個方法預設回傳原物件,因此可以一路串下去,既短又不必重複查詢。
$("#element").addClass("selected"); // 加上 class
$('#element').css({ "background-color": "yellow", "font-weight": "bolder" });
$("p").text("Some new text."); // 換掉文字內容
$("img").attr({ src: "test.jpg", alt: "Test Image" });
$("p").add("span"); // 擴充選取範圍
$("p").find("span"); // 尋找內部元素
$("p").parent(); // 取得父元素
$("p").append("<b>Hello</b>"); // 往內容尾端追加
jQuery 支援 xml、html、script、json 與 jsonp 等格式。最簡單的寫法是 .load():
// 載入靜態頁面片段
$("#feeds").load("feeds.html");
// 載入動態內容並附帶參數
$("#feeds").load("feeds.php", { limit: 25 }, function() {
alert("已載入 feed 中最後 25 筆資料");
});
需要更完整的控制時改用 $.ajax() 或 $.getJSON()。
$("p").hover(function() {
$(this).addClass("hilite"); // 游標移入
}, function() {
$(this).removeClass("hilite"); // 游標移出
});
hover() 其實是 mouseenter 與 mouseleave 的語法糖,差別在於它不會因為內部子元素觸發 mouseout 而誤觸。
$("p").show("slow"); // 漸顯
$("#go").click(function(){
$("#block").animate({
width: "90%",
height: "100%",
fontSize: "10em"
}, 1000);
});
animate() 只能動具有數值意義的 CSS 屬性,顏色需要 color 插件;若要在動畫結束後接續處理,記得傳入回呼函數作為第二個參數。
$.fn.background = function(bg){
return this.css('background', bg);
};
$('#element').background("red");
把常用操作包成 $.fn 上的方法,就能像原生前後的方法一樣用鏈式呼叫。注意一定要 return this,否則鏈條會斷掉。