jQuery中的100個(gè)技巧匯總
1.當(dāng)document文檔就緒時(shí)執(zhí)行JavaScript代碼。
我們?yōu)槭裁词褂胘Query庫呢?原因之一就在于我們可以使jQuery代碼在各種不同的瀏覽器和存在bug的瀏覽器上完美運(yùn)行。
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script> // Different ways to achieve the Document Ready event // With jQuery $(document).ready(function(){ /* ... */}); // Short jQuery $(function(){ /* ... */}); // Without jQuery (doesn't work in older IE versions) document.addEventListener('DOMContentLoaded',function(){ // Your code goes here }); // The Trickshot (works everywhere): r(function(){ alert('DOM Ready!'); }) function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} </script>
2.使用route。
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script> var route = { _routes : {}, // The routes will be stored here add : function(url, action){ this._routes[url] = action; }, run : function(){ jQuery.each(this._routes, function(pattern){ if(location.href.match(pattern)){ // "this" points to the function to be executed this(); } }); } } // Will execute only on this page: route.add('002.html', function(){ alert('Hello there!') }); route.add('products.html', function(){ alert("this won't be executed :(") }); // You can even use regex-es: route.add('.*.html', function(){ alert('This is using a regex!') }); route.run(); </script>
3.使用JavaScript中的AND技巧。
使用&&操作符的特點(diǎn)是如果操作符左邊的表達(dá)式是false,那么它就不會(huì)再判斷操作符右邊的表達(dá)式了。所以:
// Instead of writing this: if($('#elem').length){ // do something } // You can write this: $('#elem').length && log("doing something");
4. is()方法比你想象的更為強(qiáng)大。
下面舉幾個(gè)例子,我們先寫一個(gè)id為elem的div。js代碼如下:
// First, cache the element into a variable: var elem = $('#elem'); // Is this a div? elem.is('div') && log("it's a div"); // Does it have the bigbox class? elem.is('.bigbox') && log("it has the bigbox class!"); // Is it visible? (we are hiding it in this example) elem.is(':not(:visible)') && log("it is hidden!"); // Animating elem.animate({'width':200},1); // is it animated? elem.is(':animated') && log("it is animated!");
其中判斷是否為動(dòng)畫我覺得非常不錯(cuò)。
5.判斷你的網(wǎng)頁一共有多少元素。
通過使用$("*").length();方法可以判斷網(wǎng)頁的元素?cái)?shù)量。
// How many elements does your page have? log('This page has ' + $('*').length + ' elements!');
6.使用length()屬性很笨重,下面我們使用exist()方法。
/ Old way log($('#elem').length == 1 ? "exists!" : "doesn't exist!"); // Trickshot: jQuery.fn.exists = function(){ return this.length > 0; } log($('#elem').exists() ? "exists!" : "doesn't exist!");
7.jQuery方法$()實(shí)際上是擁有兩個(gè)參數(shù)的,你知道第二個(gè)參數(shù)的作用嗎?
// Select an element. The second argument is context to limit the search // You can use a selector, jQuery object or dom element $('li','#firstList').each(function(){ log($(this).html()); }); log('-----'); // Create an element. The second argument is an // object with jQuery methods to be called var div = $('<div>',{ "class": "bigBlue", "css": { "background-color":"purple" }, "width" : 20, "height": 20, "animate" : { // You can use any jQuery method as a property! "width": 200, "height":50 } }); div.appendTo('#result');
8.使用jQuery我們可以判斷一個(gè)鏈接是否是外部的,并來添加一個(gè)icon在非外部鏈接中,且確定打開方式。
這里用到了hostname屬性。
<ul id="links"> <li><a href="007.html">The previous tip</a></li> <li><a href="./009.html">The next tip</a></li> <li><a >Google</a></li> </ul> // Loop through all the links $('#links a').each(function(){ if(this.hostname != location.hostname){ // The link is external $(this).append('<img src="assets/img/external.png" />') .attr('target','_blank'); } });
9.jQuery中的end()方法可以使你的jQuery鏈更加高效。
<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul> // Here is how it is used: var breakfast = $('#meals .breakfast'); breakfast.find('.eggs').text('Yes') .end() // back to breakfast .find('.toast').text('Yes') .end() .find('.juice').toggleClass('juice coffee').text('Yes'); breakfast.find('li').each(function(){ log(this.className + ': ' + this.textContent) });
10.也許你希望你的web 應(yīng)用感覺更像原生的,那么你可以阻止contextmenu默認(rèn)事件。
<script> // Prevent right clicking on this page $(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); }); }); </script>
11.一些站點(diǎn)可能會(huì)使你的網(wǎng)頁在一個(gè)bar下面,即我們所看到在下面的網(wǎng)頁是iframe標(biāo)簽中的,我們可以這樣解決。
// Here is how it is used: if(window != window.top){ window.top.location = window.location; } else{ alert('This page is not displayed in a frame. Open 011.html to see it in action.'); }
12.你的內(nèi)聯(lián)樣式表并不是被設(shè)置為不可改變的,如下:
// Make the stylesheet visible and editable $('#regular-style-block').css({'display':'block', 'white-space':'pre'}) .attr('contentEditable',true);
這樣即可改變內(nèi)聯(lián)樣式了。
13.有時(shí)候我們不希望網(wǎng)頁的某一部分內(nèi)容被選擇比如復(fù)制粘貼這種事情,我們可以這么做:
<p class="descr">In certain situations you might want to prevent text on the page from being selectable. Try selecting this text and hit view source to see how it is done.</p> <script> // Prevent text from being selected $(function(){ $('p.descr').attr('unselectable', 'on') .css('user-select', 'none') .on('selectstart', false); }); </script>
這樣,內(nèi)容就不能被選擇啦。
14.從CDN中引入jQuery,這樣的方法可以提高我們網(wǎng)站的性能,并且引入最新的版本也是一個(gè)不錯(cuò)的主意。
下面會(huì)介紹四種不同的方法。
<!-- Case 1 - requesting jQuery from the official CDN --> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) --> <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> --> <!-- Case 3 - requesting the latest minor 1.8.x version (only cached for an hour) --> <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script> --> <!-- Case 4 - requesting the absolute latest jQuery version (use with caution) --> <!-- <script src="http://code.jquery.com/jquery.min.js"></script> -->
15.保證最小的DOM操作。
我們知道js操作DOM是非常浪費(fèi)資源的,我們可以看看下面的例子。
CODE // Bad //var elem = $('#elem'); //for(var i = 0; i < 100; i++){ // elem.append('<li>element '+i+'</li>'); //} // Good var elem = $('#elem'), arr = []; for(var i = 0; i < 100; i++){ arr.push('<li>element '+i+'</li>'); } elem.append(arr.join(''));
16.更方便的分解URL。
也許你會(huì)使用正則表達(dá)式來解析URL,但這絕對(duì)不是一種好的方法,我們可以借用a標(biāo)簽來實(shí)現(xiàn)它。
// You want to parse this address into parts: var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments'; // The trickshot: var a = $('<a>',{ href: url }); log('Host name: ' + a.prop('hostname')); log('Path: ' + a.prop('pathname')); log('Query: ' + a.prop('search')); log('Protocol: ' + a.prop('protocol')); log('Hash: ' + a.prop('hash'));
17.不要害怕使用vanilla.js。
jQuery背負(fù)的太多,這便是原因,你可以用一般的js。
// Print the IDs of all LI items $('#colors li').each(function(){ // Access the ID directly, instead // of using jQuery's $(this).attr('id') log(this.id); });
18.最優(yōu)化你的選擇器
// Let's try some benchmarks! var iterations = 10000, i; timer('Fancy'); for(i=0; i < iterations; i++){ // This falls back to a SLOW JavaScript dom traversal $('#peanutButter div:first'); } timer_result('Fancy'); timer('Parent-child'); for(i=0; i < iterations; i++){ // Better, but still slow $('#peanutButter div'); } timer_result('Parent-child'); timer('Parent-child by class'); for(i=0; i < iterations; i++){ // Some browsers are a bit faster on this one $('#peanutButter .jellyTime')
19.緩存你的selector。
// Bad: // $('#pancakes li').eq(0).remove(); // $('#pancakes li').eq(1).remove(); // $('#pancakes li').eq(2).remove(); // Good: var pancakes = $('#pancakes li'); pancakes.eq(0).remove(); pancakes.eq(1).remove(); pancakes.eq(2).remove(); // Alternatively: // pancakes.eq(0).remove().end() // .eq(1).remove().end() // .eq(2).remove().end();
20.對(duì)于重復(fù)的函數(shù)只定義一次
如果你追求代碼的更高性能,那么當(dāng)你設(shè)置事件監(jiān)聽程序時(shí)必須小心,只定義一次函數(shù)然后把它的名字作為事件處理程序傳遞是不錯(cuò)的方法。
$(document).ready(function(){ function showMenu(){ alert('Showing menu!'); // Doing something complex here } $('#menuButton').click(showMenu); $('#menuLink').click(showMenu); });
21.像對(duì)待數(shù)組一樣地對(duì)待jQuery對(duì)象
由于jQuery對(duì)象有index值和長(zhǎng)度,所以這意味著我們可以把對(duì)象當(dāng)作普通的數(shù)組對(duì)待。這樣也會(huì)有更好地性能。
var arr = $('li'), iterations = 100000; timer('Native Loop'); for(var z=0;z<iterations;z++){ var length = arr.length; for(var i=0; i < length; i++){ arr[i]; } } timer_result('Native Loop'); timer('jQuery Each'); for(z=0;z<iterations;z++){ arr.each(function(i, val) { this; }); } timer_result('jQuery Each');
未完待續(xù)...
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
使用異步controller與jQuery實(shí)現(xiàn)卷簾式分頁
這篇文章主要介紹了使用異步controller與jQuery實(shí)現(xiàn)卷簾式分頁,使用異步controller與jQuery按需加載內(nèi)容,當(dāng)用戶開始通過網(wǎng)站的內(nèi)容滾動(dòng)時(shí)進(jìn)一步加載內(nèi)容。,需要的朋友可以參考下2019-06-06JQuery Dialog對(duì)話框 不能通過Esc關(guān)閉的原因分析及解決辦法
這篇文章主要介紹了JQuery Dialog對(duì)話框 不能通過Esc關(guān)閉的原因分析及解決辦法,需要的朋友可以參考下2017-01-01由點(diǎn)擊頁面其它地方隱藏div所想到的jQuery的delegate
在網(wǎng)頁開發(fā)的過程中經(jīng)常遇到的一個(gè)需求就是點(diǎn)擊一div內(nèi)部做某些操作,而點(diǎn)擊頁面其它地方隱藏該div。比如很多導(dǎo)航菜單,當(dāng)菜單展開的時(shí)候,就會(huì)要求點(diǎn)擊頁面其它非菜單地方,隱藏該菜單2013-08-08用jQuery旋轉(zhuǎn)插件jqueryrotate制作轉(zhuǎn)盤抽獎(jiǎng)
這篇文章主要為大家詳細(xì)介紹了用jQuery旋轉(zhuǎn)插件jqueryrotate制作轉(zhuǎn)盤抽獎(jiǎng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02jqPaginator結(jié)合express實(shí)現(xiàn)分頁展示內(nèi)容效果
這篇文章主要為大家詳細(xì)介紹了jqPaginator結(jié)合express實(shí)現(xiàn)分頁展示內(nèi)容效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04jQuery實(shí)現(xiàn)氣球彈出框式的側(cè)邊導(dǎo)航菜單效果
這篇文章主要介紹了jQuery實(shí)現(xiàn)氣球彈出框式的側(cè)邊導(dǎo)航菜單效果,通過css樣式控制結(jié)合jQuery響應(yīng)鼠標(biāo)事件動(dòng)態(tài)切換元素樣式實(shí)現(xiàn)提示框效果,非常美觀實(shí)用,需要的朋友可以參考下2015-09-09jQuery插件formValidator自定義函數(shù)擴(kuò)展功能實(shí)例詳解
這篇文章主要介紹了jQuery插件formValidator自定義函數(shù)擴(kuò)展功能,結(jié)合實(shí)例形式分析了jQuery插件formValidator常見的各種判定與驗(yàn)證技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-11-11基于jquery的多彩百分比 動(dòng)態(tài)進(jìn)度條 投票效果顯示效果實(shí)現(xiàn)代碼
基于jquery的多彩百分比 動(dòng)態(tài)進(jìn)度條 投票效果顯示效果實(shí)現(xiàn)代碼,學(xué)習(xí)jquery的朋友可以參考下。2011-08-08