以下片段中,有些是 jQuery 1.4.2 起才支援的寫法,有些則是真正能幫你又快又好完成工作的實用函式與方法。這些都是我在實務中總結出的高效能片段,若你發現更好的做法,歡迎在評論中分享。希望這份整理能對你有所幫助。
1. 建立巢狀過濾器:只留下符合給定選擇器的部分。
.filter(":not(:has(.selected))")
2. 復用元素搜尋結果:
var allItems = $("div.item");
var keepList = $("div#container1 div.item");
$(formToLookAt + " input:checked").each(function() {
keepList = keepList.filter("." + $(this).attr("name"));
});
3. 用 has() 檢查元素是否包含某類或某元素:
$("input").has(".email").addClass("email_icon");
5. 依效能優化限制選擇範圍:盡量以標籤名作為類名前綴,讓搜尋更具體。
var in_stock = $('#shopping_cart_items input.is_in_stock');
6. 正確使用 toggleClass:
a.toggleClass('blueButton');
14. 用多個屬性進行過濾:
var elements = $('#someid input[type=sometype][value=somevalue]').get();
17. 找到被選中的 option 元素:
$('#someElement').find('option:selected');
18. 隱藏包含某值文字的元素:
$("p.value:contains('thetextvalue')").hide();
24. 檢查某元素是否存在:
if ($('#someDiv').length) { /* 存在 */ }
4. 切換樣式表:
$('link[media='screen']').attr('href', 'Alternative.css');
8. 替換元素:
$('#thatdiv').replaceWith('fnuh');
12. 附加 HTML 到元素:
$('#lal').append('sometext');
13. 建立元素時以物件字面量定義屬性:
var e = $("<a>", { href: "#", class: "a-class another-class", title: "..." });
28. 動態將元素加入 DOM:
var newDiv = $('<div>');
newDiv.attr('id','myNewDiv').appendTo('body');
31. 克隆元素:
var cloned = $('#somediv').clone();
35. 移除元素中的 HTML:
(function($) {
$.fn.stripHtml = function() {
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
this.each(function() {
$(this).html( $(this).html().replace(regexp,"") );
});
return $(this);
}
})(jQuery);
36. 用 closest 取得父元素:
$('#searchBox').closest('div');
40. 用 siblings() 選擇同輩元素:
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
11. 將函式綁定到事件:
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
16. 為符合選擇器的元素設定事件處理(1.4.2 起建議改用 delegate 以获得更好上下文支援):
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
19. 自動捲動到頁面某區域:
jQuery.fn.autoscroll = function(selector) {
$('html,body').animate({scrollTop: $(selector).offset().top}, 500);
}
27. 一段時間後自動隱藏元素(1.4 可用 delay):
$(".mydiv").delay(5000).hide('blind', {}, 500);
43. 取得滑鼠游標位置:
$(document).mousemove(function(e){
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
44. 將整個列表項目變成可點擊:
$("ul li").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
7. 設定 IE 專屬功能:if ($.browser.msie) { ... }
9. 驗證元素是否為空:if ($('#keks').html()) { ... }
10. 從未排序集合中取得元素索引:var index = $(this).prevAll().length;
15. 預加載圖像:
jQuery.preloadImages = function() {
for(var i = 0; i < arguments.length; i++) {
$("<img />").attr('src', arguments[i]);
}
};
20. 檢測各種瀏覽器:可透過 $.browser.safari、$.browser.msie、$.browser.mozilla 等判斷。
22. 禁用右鍵選單:
$(document).bind('contextmenu',function(e){ return false; });
23. 定義自訂選擇器:
$.expr[':'].mycustomselector = function(element, index, meta, stack){
// 包含當前元素則返回 true,否則 false
};
25. 檢測滑鼠左右鍵點擊:可透過 e.button 判斷(注意 IE 與標準瀏覽器的差異)。
26. 顯示或刪除 input 的預設值:透過 focusin/focusout 事件切換提示文字。
29. 限制 Text-Area 字元數:
jQuery.fn.maxLength = function(max){
this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type? this.type.toLowerCase() : null;
if(type == "input" && inputType == "text" || inputType == "password"){
this.maxLength = max;
} else if(type == "textarea"){
this.onkeyup = function(){
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
};
}
});
};
$('#mytextarea').maxLength(500);
32. 測試元素是否可見:if($(element).is(':visible')) { ... }
33. 將元素置於畫面中央:
jQuery.fn.center = function () {
this.css('position','absolute');
this.css('top', ( $(window).height() - this.height() ) / 2 + $(window).scrollTop() + 'px');
this.css('left', ( $(window).width() - this.width() ) / 2 + $(window).scrollLeft() + 'px');
return this;
}
37. 用 Firebug 記錄 jQuery 事件日誌:
jQuery.log = jQuery.fn.log = function (msg) {
if (console){ console.log("%s: %o", msg, this); }
return this;
};
45. 解析 XML(基本範例):
function parseXml(xml) {
$(xml).find("Tutorial").each(function() {
$("#output").append($(this).attr("author") + "");
});
}
46. 檢查圖像是否已載入完成:
$('#theImage').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
47. 為事件指定命名空間:
$('input').bind('blur.validation', function(e){ /* ... */ });
48. 檢查 cookie 是否啟用與49. 讓 cookie 過期:可透過設定 document.cookie 及 $.cookie 的 expires 選項達成。
就整理這麼多,希望對你有所幫助。