以下整理日常開發最常翻查的 jQuery 片段,依主題分類,可直接複製改用。
修改預設編碼(例如 UTF-8 改 GB2312):
$.ajaxSetup({
ajaxSettings:{ contentType:"application/x-www-form-urlencoded;chartset=GB2312"}
});
與 prototype 共存、解決 $ 衝突(順序不可顛倒,必須先 prototype 再 jQuery):
<script src="prototype.js"></script>
<script src="https:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
判斷元素是否已綁定事件(僅適用 jQuery 綁定的事件):
var $events = $("#foo").data("events");
if( $events && $events["click"] ){ /* your code */ }
動態切換樣式表:
$('link[media=screen]').attr('href', 'alternative.css');
註冊 Ajax 全域事件並顯示進度條:
$(document).ajaxStart(function(){ $("#background,#progressBar").show(); })
.ajaxStop(function(){ $("#background,#progressBar").hide(); });
單次請求若要停用全域事件,把 $.ajax() 的 global 參數設為 false。
縮小選擇範圍以優化效能——加上標籤名前綴,讓 jQuery 少繞路:
var in_stock = $('#shopping_cart_items input.is_in_stock');
用 has() 檢查元素內是否含某類別或元素(1.4 起支援):
$("input").has(".email").addClass("email_icon");
用 closest() 取得父元素:
$('#searchBox').closest('div');
用 siblings() 操作同輩(比先全部移除再自己加上更乾淨):
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
取得未排序集合中某元素的索引:
$("ul > li").click(function () { var index = $(this).prevAll().length; });
把同 name 的所有元素值收進陣列:
var arrInputValues = new Array();
$("input[name='xxx']").each(function(){ arrInputValues.push($(this).val()); });
用多屬性過濾:
var elements = $('#someid input[type=sometype][value=somevalue]').get();
建立巢狀過濾器(只留下不含 .selected 子節點的項目):
.filter(":not(:has(.selected))")
依輸入文字過濾列表:
$('.someClass').filter(function() {
return $(this).attr('value') == $('input#someId').val();
})
正確使用 toggleClass(取代 hasClass 三元判斷):
a.toggleClass('blueButton');
取代元素:
$('#thatdiv').replaceWith('fnuh');
判斷元素是否為空(兩種寫法):
if (! $('#keks').html()) { /* 空的 */ }
if ($('#keks').is(":empty")) { /* 空的 */ }
判斷元素是否存在:
if ($('#someDiv').length) { /* 存在 */ }
判斷元素是否可見:
if($(element).is(':visible')) { /* 可見 */ }
追加 HTML:
$('#lal').append('sometext');
建立元素時用物件字面值定義屬性:
var e = $("", { href: "#", class: "a-class another-class", title: "..." });
動態把新元素加入 DOM:
var newDiv = $('<div></div>');
newDiv.attr('id','myNewDiv').appendTo('body');
克隆元素:
var cloned = $('#somediv').clone();
隱藏含特定文字的元素:
$("p.value:contains('thetextvalue')").hide();
移除 HTML 標籤:
$.fn.stripHtml = function() {
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
this.each(function() { $(this).html( $(this).html().replace(regexp,'') ); });
return $(this);
}
// 用法:$('p').stripHtml();
替換字串中的詞:
var el = $('#id');
el.html(el.html().replace(/word/ig, ''));
綁定事件(兩種寫法,第二種可動態傳參):
$('#foo').click(function(event) { alert('User clicked on "foo."'); });
$('#foo').bind('click', {test1:"abc", test2:"123"}, function(event) {
alert('User clicked on "foo."' + event.data.test1 + event.data.test2 );
});
為符合選擇器的元素綁定事件(1.4.2 起建議用 delegate 取代 live,上下文支援更好):
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
為事件指定命名空間(方便日後集體解除):
$('input').bind('blur.validation', function(e){ /* ... */ });
禁用右鍵選單:
$(document).bind('contextmenu',function(e){ return false; });
區分左右鍵:
$("#someelement").bind('click', function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) { alert("Left"); }
else if(e.button == 2) { alert("Right"); }
});
取得滑鼠墊座標:
$(document).mousemove(function(e){
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
延遲執行(1.4 起)——比 setTimeout 更順手:
$(".mydiv").delay(5000).hide('blind', {}, 500);
全選/取消全選:
var tog = false;
$('a').click(function() { $("input[type=checkbox]").attr("checked",!tog); tog = !tog; });
取得已選中的 option:
$('#someElement').find('option:selected');
限制 textarea 字數:
jQuery.fn.maxLength = function(max){
return 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);
預加載圖片:
jQuery.preloadImages = function() {
for(var i = 0; i < arguments.length; i++) { $("<img />").attr('src', arguments[i]); }
};
$.preloadImages('image1.gif', '/path/to/image2.png');
檢查圖片是否載入完成:
$('#theImage').attr('src', 'image.jpg').load(function() { alert('已載入'); });
把元素置中:
jQuery.fn.center = function () {
return this.each(function(){
$(this).css({ position:'absolute',
top: ( $(window).height() - this.height() ) / 2 + $(window).scrollTop() + 'px',
left: ( $(window).width() - this.width() ) / 2 + $(window).scrollLeft() + 'px' });
});
}
$(element).center();
自訂選擇器:
$.expr[':'].mycustomselector = function(element, index, meta, stack){
return true; // 包含目前元素就回傳 true
}
$('.someClasses:test').doSomething();
規範的插件寫法:
(function($){
$.fn.extend({
pluginOne: function(){ return this.each(function(){ /* my code */ }); },
pluginTwo: function(){ return this.each(function(){ /* my code */ }); }
});
})(jQuery);
擴充 String 原型(驗證整數、郵件、網址、電話等):
$.extend(String.prototype, {
isInteger:function(){ return (new RegExp(/^\d+$/).test(this)); },
trim:function(){ return this.replace(/(^\s*)|(\s*$)|\r|\n/g, ""); },
replaceAll:function(os, ns) { return this.replace(new RegExp(os,"gm"),ns); },
isValidMail:function(){ return (new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim())); },
isUrl:function(){ return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this)); }
});
把純文字 URL 轉成可點連結:
$.fn.replaceUrl = function() {
var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
return this.each(function() { $(this).html( $(this).html().replace(regexp,'<a href="$1">$1</a>') ); });
}
$('p').replaceUrl();
用 Firebug 記錄 jQuery 事件日誌(可鏈式):
jQuery.log = jQuery.fn.log = function (msg) {
if (console){ console.log("%s: %o", msg, this); }
return this;
};
$('#someDiv').hide().log('div hidden').addClass('someClass');
檢查 cookie 是否啟用:
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
強制在新視窗/新分頁開啟連結:
$('a.popup').bind('click', function(){
var newwindow = window.open($(this).attr('href'),'','height=200,width=150');
if (window.focus) { newwindow.focus(); }
return false;
});
這批片段中用到 $.browser 的寫法(如第 7、20、25 條)在 jQuery 1.9 之後已被移除,新專案請改用 Modernizr 或直接判斷 navigator.userAgent;.live() 也應替換為 .on()。