以下整理日常開發最常回頭查的十二類操作,每一類都附可直接複製的範例。
jQuery 的 $() 支援 id、class、元素名、層級關係、DOM 或 XPath 條件等多種寫法,回傳的是 jQuery 集合物件,因此不能直接呼叫 DOM 原生方法。
只有 jQuery 物件才能使用 jQuery 方法,兩者不可混用。DOM 物件可以隨時包成 jQuery 物件:
$(document.getElementById("msg")) // → jQuery 物件,可用 jQuery 方法
反之,jQuery 物件本身是集合,要轉回 DOM 必須取出其中一項:
$("#msg")[0]
$("div").eq(1)[0]
$("div").get()[1]
$("td")[5]
以下寫法都正確:
$("#msg").html(); // jQuery 方法
$("#msg")[0].innerHTML; // DOM 屬性
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;
eq(n) 回傳 jQuery 物件,get(n) 與 [n] 回傳 DOM 元素。這個差異是無數 bug 的來源,務必記牢:
$("div").eq(2).html(); // 之後可續用 jQuery 方法
$("div").get(2).innerHTML; // 之後只能用 DOM 屬性
jQuery 大量採用這個模式:不帶參數是取值,帶參數是設值。
$("#msg").html(); // 取得 HTML 內容
$("#msg").html("<b>new content</b>"); // 寫入 HTML(會被解析)
$("#msg").text(); // 取得純文字
$("#msg").text("<b>new content</b>"); // 寫入純文字(原樣顯示)
$("#msg").height(); $("#msg").height("300");
$("#msg").width(); $("#msg").width("300");
$("input").val(); $("input").val("test");
$("#msg").click(); // 觸發點擊
$("#msg").click(fn); // 綁定點擊
blur、focus、select、submit 都同樣有這兩種用法。
不必自己寫迴圈:
$("p").each(function(i){ this.style.color = ['#f00','#0f0','#00f'][ i ]; });
$("tr").each(function(i){ this.style.backgroundColor = ['#ccc','#fff'][i % 2]; }); // 隔行換色
$("p").click(function(){ alert($(this).html()); }); // 逐個綁事件
$.extend({
min: function(a, b){ return a < b ? a : b; },
max: function(a, b){ return a > b ? a : b; }
});
alert("a=10,b=20,max=" + $.max(10,20) + ",min=" + $.min(10,20));
$("p")
.click(function(){ alert($(this).html()); })
.mouseover(function(){ alert('mouse over event'); })
.each(function(i){ this.style.color = ['#f00','#0f0','#00f'][ i ]; });
$("#msg").css("background"); // 取得背景色
$("#msg").css("background", "#ccc"); // 設定背景
$("#msg").height(300).width("200");
$("#msg").css({ color: "red", background: "blue" });
$("#msg").addClass("select");
$("#msg").removeClass("select");
$("#msg").toggleClass("select"); // 有則移除、無則加上
不必在 HTML 上寫 onclick,直接用 jQuery 綁:
$("#msg").click(function(){ alert("good"); });
$("p").click(function(i){ this.style.color = ['#f00','#0f0','#00f'][ i ]; });
幾個自訂事件:
hover(fn1, fn2) 滑入執行 fn1、滑出執行 fn2。
$("tr").hover(
function(){ $(this).addClass("over"); },
function(){ $(this).removeClass("out"); }
);
ready(fn) DOM 就緒即可操作,等同 $(fn)。
$(document).ready(function(){ alert("Load Success"); });
toggle(evenFn, oddFn) 每次點擊輪流執行兩個函式。
$("p").toggle(
function(){ $(this).addClass("selected"); },
function(){ $(this).removeClass("selected"); }
);
trigger(事件) 主動觸發事件。
$("p").trigger("click");
bind / unbind 綁定與解除。
$("p").bind("click", function(){ alert($(this).text()); });
$("p").unbind(); // 移除所有事件
$("p").unbind("click"); // 只移除 click
toggle() 與 slideToggle() 提供狀態切換:前者包含 hide/show,後者包含 slideDown/slideUp。
$.browser 瀏覽器偵測(safari、opera、msie、mozilla)。注意:此 API 已於 jQuery 1.9 移除,請改用 navigator.userAgent 或 Modernizr 做功能偵測。
$.each(obj, fn) 通用迭代器,可處理陣列與物件:
$.each([0,1,2], function(i, n){ alert("Item #" + i + ": " + n); });
$.each({ name: "John", lang: "JS" }, function(i, n){
alert("Name: " + i + ", Value: " + n);
});
$.extend(target, prop1, propN) 合併物件,是 jQuery 的繼承機制:
$.extend(settings, options); // 併入 settings(會覆蓋)
var settings = $.extend({}, defaults, options); // 保留 defaults 不被改動
$.map(array, fn) 陣列映射,回傳 null 的項目會被濾掉:
var a = $.map([0,1,2], function(i){ return i + 4; }); // [4,5,6]
var b = $.map([0,1,2], function(i){ return i > 0 ? i+1 : null; }); // [2,3]
$.merge(arr1, arr2) 合併兩個陣列並去除重複:
$.merge([0,1,2], [2,3,4]); // [0,1,2,3,4]
$.trim(str) 移除字串兩端空白:
$.trim(" hello, how are you? ");
Prototype、MooTools 等函式庫也定義了 $,同時載入就會衝突。jQuery 提供了官方解法:
jQuery.noConflict();
jQuery("div p").hide(); // 改用 jQuery
$("content").style.display = 'none'; // $ 還給其他函式庫
更常見的做法是傳入 IIFE 取得專屬的 $:
(function($){
$(document).ready(function(){ /* 這裡的 $ 一定是 jQuery */ });
})(jQuery);
以上多數寫法在 jQuery 3.x 仍然可用,但有幾項需要更新:.bind()/.unbind()/.live()/.delegate() 已統一為 .on()/.off();$.browser 已移除;.attr("checked") 判斷狀態應改用 .prop();.size() 已棄用,改用 .length。若你的專案仍在 jQuery 1.x,上述範例可直接使用;若已升級,建議照這份對照表逐項替換,並養成寫新程式時直接查官方文件的習慣——API 會變,查文件的能力不會。