本文會給你們展示50個jquery代碼片段,這些代碼能夠給你的javascript項目提供幫助。其中的一些代碼段是從jQuery1.4.2才開始支持的做法,另一些則是真正有用的函數或方法,他們能夠幫助你又快又好地把事情完成。如果你發現你任何可以做得更好的地方的話,歡迎把你的版本粘貼在評論中!
1. 如何修改jQuery默認編碼(例如默認UTF-8改成改GB2312):
$.ajaxSetup({ ajaxSettings:{ contentType:"application/x-www-form-urlencoded;chartset=GB2312"} });
2. 解決jQuery, prototype共存,$全局變量沖突問題:
<script src="prototype.js"></script> <script src="http://blogbeta.blueidea.com/jquery.js"></script> <script type="text/javascript"> jQuery.noConflict(); </script>
注意:一定要先引入prototype.js 再引入jquery.js,先后順序不可錯。
3. jQuery 判斷元素上是否綁定了事件
//jQuery event封裝支持判斷元素上是否綁定了事件,此方法只適用於jQuery綁定的事件var $events = $("#foo").data("events"); if( $events && $events["click"] ){ //your code}
4. 如何使用jQuery來切換樣式表
//找出你希望切換的媒體類型(media-type),然后把href設置成新的樣式表。$('link[media='screen']').attr('href', 'alternative.css');
5. 如何限制選擇范圍(基於優化目的):
//盡可能使用標簽名來作為類名的前綴, //這樣jQuery就不需要花費更多的時間來搜索 //你想要的元素。還要記住的一點是, //針對於你的頁面上的元素的操作越具體化, //就越能降低執行和搜索的時間。var in_stock = $('#shopping_cart_items input.is_in_stock'); <ul id="shopping_cart_items"> <li><input type="radio" value="Item-X" name="item" class="is_in_stock" /> Item X</li> <li><input type="radio" value="Item-Y" name="item" class="3-5_days" /> Item Y</li> <li><input type="radio" value="Item-Z" name="item" class="unknown" /> Item Z</li> </ul>
6. 如何正確地使用toggleClass:
//切換(toggle)類允許你根據某個類的 //是否存在來添加或是刪除該類。 //這種情況下有些開發者使用:a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton'); //toggleClass允許你使用下面的語句來很容易地做到這一點a.toggleClass('blueButton');
7. 如何設置IE特有的功能:
if ($.browser.msie) { // Internet Explorer就是個虐待狂}
8. 如何使用jQuery來代替一個元素:
$('#thatdiv').replaceWith('fnuh');
9. 如何驗證某個元素是否為空:
// 方法一if (! $('#keks').html()) { //什么都沒有找到;} // 方法二if ($('#keks').is(":empty")) { //什么都沒有找到;}
10. 如何從一個未排序的集合中找出某個元素的索引號
$("ul > li").click(function () { var index = $(this).prevAll().length; //prevAll([expr]): 查找當前元素之前所有的同輩元素});
11. 如何把函數綁定到事件上:
//方法一$('#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 ); });
12. 如何追加或是添加html到元素中:
$('#lal').append('sometext');
13. 在創建元素時,如何使用對象字面量(literal)來定義屬性
var e = $("", { href: "#", class: "a-class another-class", title: "..." });
14. 如何使用多個屬性來進行過濾
//在使用許多相類似的有着不同類型的input元素時, //這種基於精確度的方法很有用 var elements = $('#someid input[type=sometype][value=somevalue]').get();
15. 如何使用jQuery來預加載圖像:
jQuery.preloadImages = function() { for(var i = 0; i < arguments.length; i++) { $("<img />").attr('src', arguments[i]); } }; //用法 $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');
16. 如何為任何與選擇器相匹配的元素設置事件處理程序:
$('button.someClass').live('click', someFunction); //注意,在jQuery 1.4.2中,delegate和undelegate選項 //被引入代替live,因為它們提供了更好的上下文支持 //例如,就table來說,以前你會用$("table").each(function(){ $("td", this).live("hover", function(){ $(this).toggleClass("hover"); }); }); //現在用 $("table").delegate("td", "hover", function(){ $(this).toggleClass("hover"); });
17. 如何找到一個已經被選中的option元素:
$('#someElement').find('option:selected');
18. 如何隱藏一個包含了某個值文本的元素:
$("p.value:contains('thetextvalue')").hide();
19. 如何創建嵌套的過濾器:
//允許你減少集合中的匹配元素的過濾器, //只剩下那些與給定的選擇器匹配的部分。在這種情況下, //查詢刪除了任何沒(:not)有(:has) //包含class為“selected”(.selected)的子節點。.filter(":not(:has(.selected))")
20. 如何檢測各種瀏覽器:
檢測Safari (if( $.browser.safari)),
檢測IE6及之后版本 (if ($.browser.msie && $.browser.version > 6 )),
檢測IE6及之前版本 (if ($.browser.msie && $.browser.version <= 6 )),
檢測FireFox 2及之后版本 (if ($.browser.mozilla && $.browser.version >= '1.8' ))
21. 任何使用has()來檢查某個元素是否包含某個類或是元素:
//jQuery 1.4.*包含了對這一has方法的支持。 //該方法找出某個元素是否包含了其他另一個元素類或是其他任何的你正在查找並要在其之上進行操作的東東。$("input").has(".email").addClass("email_icon");
22. 如何禁用右鍵單擊上下文菜單:
$(document).bind('contextmenu',function(e){ return false; });
23. 如何定義一個定制的選擇器
$.expr[':'].mycustomselector = function(element, index, meta, stack){ // element- 一個DOM元素 // index – 棧中的當前循環索引 // meta – 有關選擇器的元數據 // stack – 要循環的所有元素的棧 // 如果包含了當前元素就返回true // 如果不包含當前元素就返回false }; // 定制選擇器的用法: $('.someClasses:test').doSomething();
24. 如何檢查某個元素是否存在
if ($('#someDiv').length) { //萬歲!!!它存在…… }
25. 如何使用jQuery來檢測右鍵和左鍵的鼠標單擊兩種情況:
$("#someelement").live('click', function(e) { if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) { alert("Left Mouse Button Clicked"); } else if(e.button == 2) { alert("Right Mouse Button Clicked"); } });
26. 如何替換串中的詞
var el = $('#id');
el.html(el.html().replace(/word/ig, ''));
27. 如何在一段時間之后自動隱藏或關閉元素(支持1.4版本):
//這是1.3.2中我們使用setTimeout來實現的方式 setTimeout(function() { $('.mydiv').hide('blind', {}, 500) }, 5000); //而這是在1.4中可以使用delay()這一功能來實現的方式(這很像是休眠) $(".mydiv").delay(5000).hide('blind', {}, 500);
28. 如何把已創建的元素動態地添加到DOM中:
var newDiv = $('<div></div>');
newDiv.attr('id','myNewDiv').appendTo('body');
29. 如何限制“Text-Area”域中的字符的個數:
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"){ //Apply the standard maxLength this.maxLength = max; } else if(type == "textarea"){ this.onkeypress = function(e){ var ob = e || event; var keyCode = ob.keyCode; var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); }; this.onkeyup = function(){ if(this.value.length > max){ this.value = this.value.substring(0,max); } }; } }); }; //用法 $('#mytextarea').maxLength(500);
30. 如何jQuery注冊和禁用jQuery全局事件
//jQuery注冊ajax全局事件ajaxStart,ajaxStop:$(document).ajaxStart(function(){ $("#background,#progressBar").show(); }).ajaxStop(function(){ $("#background,#progressBar").hide(); }); //ajax請求禁用全局事件:$.ajax() 有個參數global (默認: true) 是否觸發全局 AJAX 事件.設置為 false 將不會觸發全局 AJAX 事件,如 ajaxStart 或 ajaxStop 可用於控制不同的 Ajax 事件。
31. 如何在jQuery中克隆一個元素:
var cloned = $('#somediv').clone();
32. 在jQuery中如何測試某個元素是否可見
if($(element).is(':visible')) { //該元素是可見的 }
33. 如何把一個元素放在屏幕的中心位置:
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();
34. 如何把有着某個特定名稱的所有元素的值都放到一個數組中:
var arrInputValues = new Array(); $("input[name='xxx']").each(function(){ arrInputValues.push($(this).val()); });
35. 如何從元素中除去HTML
(function($) { $.fn.stripHtml = function() { var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function() { $(this).html( $(this).html().replace(regexp,'') ); }); return $(this); } })(jQuery); //用法: $('p').stripHtml();
36. 如何使用closest來取得父元素:
$('#searchBox').closest('div');
37. 如何使用Firebug和Firefox來記錄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');
38. 如何強制在彈出窗口中打開鏈接:
$('a.popup').live('click', function(){ var newwindow = window.open($(this).attr('href'),'','height=200,width=150'); if (window.focus) { newwindow.focus(); } return false; });
39. 如何強制在新的選項卡中打開鏈接:
$('a.newTab').live('click', function(){ var newwindow=window.open(this.href); $(this).target = "_blank"; return false; });
40. 在jQuery中如何使用.siblings()來選擇同輩元素
// 不這樣做 $('#nav li').click(function(){ $('#nav li').removeClass('active'); $(this).addClass('active'); }); //替代做法是 $('#nav li').click(function(){ $(this).addClass('active').siblings().removeClass('active'); });
41. 如何切換頁面上的所有復選框:
var tog = false; // 或者為true,如果它們在加載時為被選中狀態的話 $('a').click(function() { $("input[type=checkbox]").attr("checked",!tog); tog = !tog; });
42. 如何基於一些輸入文本來過濾一個元素列表:
//如果元素的值和輸入的文本相匹配的話,該元素將被返回 $('.someClass').filter(function() { return $(this).attr('value') == $('input#someId').val(); })
43. 如何獲得鼠標墊光標位置x和y
$(document).ready(function() { $(document).mousemove(function(e){ $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY); }); });
44. 如何擴展String對象的方法
$.extend(String.prototype, { isPositiveInteger:function(){ return (new RegExp(/^[1-9]\d*$/).test(this)); }, isInteger:function(){ return (new RegExp(/^\d+$/).test(this)); }, isNumber: function(value, element) { return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this)); }, trim:function(){ return this.replace(/(^\s*)|(\s*$)|\r|\n/g, ""); }, trans:function() { return this.replace(/</g, '<').replace(/>/g,'>').replace(/"/g, '"'); }, replaceAll:function(os, ns) { return this.replace(new RegExp(os,"gm"),ns); },
skipChar:function(ch) { if (!this || this.length===0) {return '';} if (this.charAt(0)===ch) {return this.substring(1).skipChar(ch);} return this; }, isValidPwd:function() { return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this)); }, isValidMail:function(){ return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim())); }, isSpaces:function() { for(var i=0; i<this.length; i+=1) { var ch = this.charAt(i); if (ch!=' '&& ch!="\n" && ch!="\t" && ch!="\r") {return false;} } return true; }, isPhone:function() { return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this)); }, isUrl:function(){ return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this)); }, isExternalUrl:function(){ return this.isUrl() && this.indexOf("://"+document.domain) == -1; } });
45. 如何規范化寫jQuery插件:
(function($){ $.fn.extend({ pluginOne: function(){ return this.each(function(){ // my code }); }, pluginTwo: function(){ return this.each(function(){ // my code }); } }); })(jQuery);
46. 如何檢查圖像是否已經被完全加載進來
$('#theImage').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
47. 如何使用jQuery來為事件指定命名空間:
//事件可以這樣綁定命名空間 $('input').bind('blur.validation', function(e){ // ... }); //data方法也接受命名空間 $('input').data('validation.isValid', true);
48. 如何檢查cookie是否啟用
var dt = new Date(); dt.setSeconds(dt.getSeconds() + 60); document.cookie = "cookietest=1; expires=" + dt.toGMTString(); var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1; if(!cookiesEnabled) { //沒有啟用cookie }
49. 如何讓cookie過期:
var date = new Date(); date.setTime(date.getTime() + (x * 60 * 1000)); $.cookie('example', 'foo', { expires: date });
50. 如何使用一個可點擊的鏈接來替換頁面中任何的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();
----------------------------------------------------------------
1.預加載圖片
function($) { var cache = []; // Arguments are image paths relative to the current page. $.preLoadImages = function() { var args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } } jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
2. 讓頁面中的每個元素都適合在移動設備上展示
var scr = document.createElement('script'); scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'); document.body.appendChild(scr); scr.onload = function(){ $('div').attr('class', '').attr('id', '').css({ 'margin' : 0, 'padding' : 0, 'width': '100%', 'clear':'both' }); };
3.圖像等比例縮放
$(window).bind("load", function() { // IMAGE RESIZE $('#product_cat_list img').each(function() { var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $(this).width(); var height = $(this).height(); if(width > maxWidth){ ratio = maxWidth / width; $(this).css("width", maxWidth); $(this).css("height", height * ratio); height = height * ratio; } var width = $(this).width(); var height = $(this).height(); if(height > maxHeight){ ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; } }); //$("#contentpage img").show(); // IMAGE RESIZE });
4.返回頁面頂部
// Back To Top $(document).ready(function(){ $('.top').click(function() { $(document).scrollTo(0,500); }); }); //Create a link defined with the class .top <a href="#" class="top">Back To Top</a>
5.使用jQuery打造手風琴式的折疊效果
var accordion = { init: function(){ var $container = $('#accordion'); $container.find('li:not(:first) .details').hide(); $container.find('li:first').addClass('active'); $container.on('click','li a',function(e){ e.preventDefault(); var $this = $(this).parents('li'); if($this.hasClass('active')){ if($('.details').is(':visible')) { $this.find('.details').slideUp(); } else { $this.find('.details').slideDown(); } } else { $container.find('li.active .details').slideUp(); $container.find('li').removeClass('active'); $this.addClass('active'); $this.find('.details').slideDown(); } }); } };
6.通過預加載圖片廊中的上一幅下一幅圖片來模仿Facebook的圖片展示方式
var nextimage = "/images/some-image.jpg"; $(document).ready(function(){ window.setTimeout(function(){ var img = $("").attr("src", nextimage).load(function(){ //all done }); }, 100); });
7.使用jQuery和Ajax自動填充選擇框
$(function(){ $("select#ctlJob").change(function(){ $.getJSON("/select.php", { id: $(this).val(), ajax: 'true' }, function(j){ var options = ''; for (var i = 0; i < j.length; i++) { options += '' + j[i].optionDisplay + ''; } $("select#ctlPerson").html(options); }); }); });
8.自動替換丟失的圖片
// Safe Snippet $("img").error(function () { $(this).unbind("error").attr("src", "missing_image.gif"); }); // Persistent Snipper $("img").error(function () { $(this).attr("src", "missing_image.gif"); });
9.在鼠標懸停時顯示淡入/淡出特效
$(document).ready(function(){ $(".thumbs img").fadeTo("slow", 0.6);// This sets the opacity of the thumbs to fade down to 60% when the page loads $(".thumbs img").hover(function(){ $(this).fadeTo("slow", 1.0);// This should set the opacity to 100% on hover },function(){ $(this).fadeTo("slow", 0.6);// This should set the opacity back to 60% on mouseout }); });
10.清空表單數據
function clearForm(form) { // iterate over all of the inputs for the form // element that was passed in $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase();// normalize case // it's ok to reset the value attr of text inputs, // password inputs, and textareas if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ""; // checkboxes and radios need to have their checked state cleared // but should *not* have their 'value' changed else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = -1; }); };
11.預防對表單進行多次提交
$(document).ready(function() { $('form').submit(function() { if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') { jQuery.data(this, "disabledOnSubmit", { submited: true }); $('input[type=submit], input[type=button]', this).each(function() { $(this).attr("disabled", "disabled"); }); return true; } else { return false; } }); });
12.動態添加表單元素
//change event on password1 field to prompt new input $('#password1').change(function() { //dynamically create new input and insert after password1 $("#password1").append(""); });
13.讓整個Div可點擊
//blah blah blah. link //The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location = $(this).find("a").attr("href"); return false; });
14.平衡高度或Div元素
var maxHeight = 0; $("div").each(function(){ if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } }); $("div").height(maxHeight);
15. 在窗口滾動時自動加載內容
var loading = false; $(window).scroll(function(){ if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){ if(loading == false){ loading = true; $('#loadingbar').css("display","block"); $.get("load.php?start="+$('#loaded_max').val(), function(loaded){ $('body').append(loaded); $('#loaded_max').val(parseInt($('#loaded_max').val())+50); $('#loadingbar').css("display","none"); loading = false; }); } } }); $(document).ready(function() { $('#loaded_max').val(50); });