1.當document文檔就緒時執行JavaScript代碼。css
咱們爲何使用jQuery庫呢?緣由之一就在於咱們可使jQuery代碼在各類不一樣的瀏覽器和存在bug的瀏覽器上完美運行。html
<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。jquery
<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技巧。web
使用&&操做符的特色是若是操做符左邊的表達式是false,那麼它就不會再判斷操做符右邊的表達式了。因此:ajax
// Instead of writing this: if($('#elem').length){ // do something } // You can write this: $('#elem').length && log("doing something");
4. is()方法比你想象的更爲強大。正則表達式
下面舉幾個例子,咱們先寫一個id爲elem的div。js代碼以下:api
// 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.判斷你的網頁一共有多少元素。瀏覽器
經過使用$("*").length();方法能夠判斷網頁的元素數量。緩存
// 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方法$()其實是擁有兩個參數的,你知道第二個參數的做用嗎?
// 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咱們能夠判斷一個連接是不是外部的,並來添加一個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 href="http://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.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 應用感受更像原生的,那麼你能夠阻止contextmenu默認事件。
<script> // Prevent right clicking on this page $(function(){ $(document).on("contextmenu",function(e){ e.preventDefault(); }); }); </script>
11.一些站點可能會使你的網頁在一個bar下面,即咱們所看到在下面的網頁是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="http://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="http://code.jquery.com/jquery.min.js"></script> -->
15.保證最小的DOM操做。
咱們知道js操做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。
也許你會使用正則表達式來解析URL,但這絕對不是一種好的方法,咱們能夠借用a標籤來實現它。
// 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揹負的太多,這即是緣由,你能夠用通常的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.最優化你的選擇器
// 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.對於重複的函數只定義一次
若是你追求代碼的更高性能,那麼當你設置事件監聽程序時必須當心,只定義一次函數而後把它的名字做爲事件處理程序傳遞是不錯的方法。
$(document).ready(function(){ function showMenu(){ alert('Showing menu!'); // Doing something complex here } $('#menuButton').click(showMenu); $('#menuLink').click(showMenu); });
21.像對待數組同樣地對待jQuery對象
因爲jQuery對象有index值和長度,因此這意味着咱們能夠把對象看成普通的數組對待。這樣也會有更好地性能。
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');
22.當作複雜的修改時要分離元素。
修改一個dom元素要求網頁重繪,這個代價是高昂的,因此若是你想要再提升性能,就能夠嘗試着當對一個元素進行大量修改時先從頁面中分離這個元素,修改完以後再添加到頁面。
// Modifying in place var elem = $('#elem'); timer('In place'); for(i=0; i < iterations; i++){ elem.width(Math.round(100*Math.random())); elem.height(Math.round(100*Math.random())); } timer_result('In place'); var parent = elem.parent(); // Detaching first timer('Detached'); elem.detach(); for(i=0; i < iterations; i++){ elem.width(Math.round(100*Math.random())); elem.height(Math.round(100*Math.random())); } elem.appendTo(parent); timer_result('Detached');
23.不要一直等待load事件。
咱們已經習慣了把咱們全部的代碼都放在ready的事件處理程序中,可是,若是你的html頁面很龐大,decument ready恐怕會被延遲了,因此對於一些咱們不但願ready後才能夠觸發的事件能夠放在html的head元素中。
<script> // jQuery is loaded at this point. We can use // event delegation right away to bind events // even before $(document).ready: $(document).on('click', '#clickMe', function(){ alert('Hit view source and see how this is made'); }); $(document).ready(function(){ // This is where you would usually bind event handlers, // but as we are using delegation, there is no need to. // $('#clickMe').click(function(){ alert('Hey!'); }); }); // Note: You should place your script tags at the bottom of the page. // I have included them in the head only to demonstrate that we can bind // events before document ready and before the elements are created. </script>
24.當使用js給多個元素添加樣式時更好的作法是建立一個style元素。
咱們以前提到過,操做dom是很是慢的,因此當添加多個元素的樣式時建立一個style元素並添加到document中是更好的作法。
<ul id="testList"> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> </ul> var style = $('<style>'); // Try commenting out this line, or change the color: style.text('#testList li{ color:red;}'); // Placing it before the result section so it affects the elements style.prependTo('#result');
25.給html元素分配一個名爲JS的class。
現代的web apps很是的依賴js,這裏的一個技巧就是隻有當js可用時才能顯示特定的元素。看下面的代碼。
$(document).ready(function(){ $('html').addClass('JS'); }); html.JS #message { display:block; } #message {display:none;}
這樣,只有js可用的時候id爲message的元素纔會顯示;若是不支持js,則該元素不會顯示。
26.監聽不存在的元素上的事件。
jQuery擁有一個先進的事件處理機制,經過on()方法能夠監聽還不存在的事件。 這是由於on方法能夠傳遞一個元素的子元素選擇器做爲參數。看下面的例子:
<ul id="testList"> <li>Old</li> <li>Old</li> <li>Old</li> <li>Old</li> </ul> var list = $('#testList'); // Binding an event on the list, but listening for events on the li items: list.on('click','li',function(){ $(this).remove(); }); // This allows us to create li elements at a later time, // while keeping the functionality in the event listener list.append('<li>New item (click me!)</li>');
這樣,即便li是後建立的,也能夠經過on()方法來監聽。
27.只使用一次事件監聽。
有時,咱們只須要綁定只運行一次的事件處理程序。那麼one()方法是一個不錯的選擇,經過它你就能夠高枕無憂了。
<button id="press">Press me!</ul> var press = $('#press'); // There is a method that does exactly that, the one(): press.one('click',function(){ alert('This alert will pop up only once'); }); // What this method does, is call on() behind the scenes, // with a 1 as the last argument: // press.on('click',null,null,function(){alert('I am the one and only!');}, 1);
28.模擬觸發事件。
咱們能夠經過使用trigger模擬觸發一個click事件。
<button id="press">Press me!</ul> var press = $('#press'); // Just a regular event listener: press.on('click',function(e, how){ how = how || ''; alert('The buton was clicked ' + how + '!'); }); // Trigger the click event press.trigger('click'); // Trigger it with an argument press.trigger('click',['fast']);
29.使用觸摸事件。
使用觸摸事件和相關的鼠標事件並無太多不一樣,可是你得有一個方便的移動設備來測試會更好。看下面這個例子。
// Define some variables var ball = $('<div id="ball"></div>').appendTo('body'), startPosition = {}, elementPosition = {}; // Listen for mouse and touch events ball.on('mousedown touchstart',function(e){ e.preventDefault(); // Normalizing the touch event object e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; // Recording current positions startPosition = {x: e.pageX, y: e.pageY}; elementPosition = {x: ball.offset().left, y: ball.offset().top}; // These event listeners will be removed later ball.on('mousemove.rem touchmove.rem',function(e){ e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; ball.css({ top:elementPosition.y + (e.pageY - startPosition.y), left: elementPosition.x + (e.pageX - startPosition.x), }); }); }); ball.on('mouseup touchend',function(){ // Removing the heavy *move listeners ball.off('.rem'); });
30.更好地使用on()/off()方法。
在jQuery1.7版本時對事件處理進行了簡化,看看下面的例子吧。
<div id="holder"> <button id="button1">1</button> <button id="button2">2</button> <button id="button3">3</button> <button id="button4">4</button> <button id="clear" style="float: right;">Clear</button> </div> // Lets cache some selectors var button1 = $('#button1'), button2 = $('#button2'), button3 = $('#button3'), button4 = $('#button4'), clear = $('#clear'), holder = $('#holder'); // Case 1: Direct event handling button1.on('click',function(){ log('Click'); }); // Case 2: Direct event handling of multiple events button2.on('mouseenter mouseleave',function(){ log('In/Out'); }); // Case 3: Data passing button3.on('click', Math.round(Math.random()*20), function(e){ // This will print the same number over and over again, // as the random number above is generated only once: log('Random number: ' + e.data); }); // Case 4: Events with a namespace button4.on('click.temp', function(e){ log('Temp event!'); }); button2.on('click.temp', function(e){ log('Temp event!'); }); // Case 5: Using event delegation $('#holder').on('click', '#clear', function(){ log.clear(); }); // Case 6: Passing an event map var t; // timer clear.on({ 'mousedown':function(){ t = new Date(); }, 'mouseup':function(){ if(new Date() - t > 1000){ // The button has been held pressed // for more than a second. Turn off // the temp events $('button').off('.temp'); alert('The .temp events were cleared!'); } } });
31.更快地阻止默認事件行爲。
咱們知道js中可使用preventDefault()方法來阻止默認行爲,可是jQuery對此提供了更簡單的方法。以下:
<a href="http://google.com/" id="goToGoogle">Go To Google</a> $('#goToGoogle').click(false);
32.使用event.result連接多個事件處理程序。
對一個元素綁定多個事件處理程序並不常見,而使用event.result更能夠將多個事件處理程序聯繫起來。看下面的例子。
<button id="press">點擊</button> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script> var press = $('#press'); press.on('click',function(){ return 'Hip'; }); // The second event listener has access // to what was returned from the first press.on('click',function(e){ console.log(e.result + ' Hop!'); }); </script>
這樣,控制檯會輸出Hip Hop!
33.建立你本身習慣的事件。
你可使用on()方法建立本身喜歡的事件名稱,而後經過trigger來觸發。舉例以下:
<button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script> var button1 = $('#button1'), button2 = $('#button2'), button3 = $('#button3'), clear = $('#clear'), div = $('#eventDiv'); div.on({ jump : function(){ alert('Jumped!'); }, punch : function(e,data){ alert('Punched '+data+'!'); }, click : function(){ alert('Simulated click!'); } }); button1.click(function(){ div.trigger('jump'); }); button2.click(function(){ // Pass data along with the event div.trigger('punch',['hard']); }); button3.click(function(){ div.trigger('click'); }); clear.click(function(){ log.clear(); }); </script>
持續更新中...
注:原創文章,如需轉載,請註明出處。博客地址:http://www.cnblogs.com/zhuzhenwei918/p/6181760.html