1. 當 document 文檔就緒時執行 JavaScript 代碼。
我們之所以使用 jQuery 庫,原因之一就在於它能讓 jQuery 代碼在各種瀏覽器(包括存在 bug 的瀏覽器)上完美運行。
<script src="https://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="https://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 技巧。
&& 操作符的特點是:若左邊的表達式為 false,就不會再判斷右邊的表達式,因此:
// Instead of writing this: if($('#elem').length){ // do something } // You can write this: $('#elem').length && log("doing something");
4. is() 方法比你想像的更強大。
// 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!");
其中判斷是否為動畫這一點我覺得非常實用。
5. 判斷你的網頁一共有多少元素。
// How many elements does your page have? log('This page has ' + $('*').length + ' elements!');
6. 用 exist() 方法取代笨重的 length 判斷。
/ 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. $() 實際上有兩個參數,你知道第二個參數的作用嗎?
// 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. 判斷鏈接是否為外部鏈接,並為非外部鏈接加上圖示、決定開啟方式。
<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 href="https://www.google.com/">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. 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 應用更像原生的做法之一:阻止 contextmenu 預設事件。
<script> // Prevent right clicking on this page $(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); }); }); </script>
11. 防止網頁被嵌在其他網站的 iframe 中。
// 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. 內聯樣式表並非不可改變。
// Make the stylesheet visible and editable $('#regular-style-block').css({'display':'block', 'white-space':'pre'}) .attr('contentEditable',true);
13. 防止網頁某部分內容被選取(例如避免被複製貼上)。
<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>
14. 從 CDN 引入 jQuery,可提升網站效能,也能方便取得最新版本。
<!-- Case 1 - requesting jQuery from the official CDN --> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) --> <!-- <script src="//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="//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="https://code.jquery.com/jquery.min.js"></script> -->
15. 盡量減少 DOM 操作。
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。
// You want to parse this address into parts: var url = 'https://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. 別害怕使用原生 JavaScript。
// 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. 優化你的選擇器。
// 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. 快取你的選擇器。
// 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. 對於重複的函式只定義一次。
$(document).ready(function(){ function showMenu(){ alert('Showing menu!'); // Doing something complex here } $('#menuButton').click(showMenu); $('#menuLink').click(showMenu); });
21. 像對待陣列一樣對待 jQuery 物件。
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');
以上就是本次整理的精選技巧,希望對你的學習或工作有所幫助。