jQuery中的常用到的三十九个技巧

开发 后端
我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上完美运行。

1.当document文档就绪时执行JavaScript代码。

我们为什么使用jQuery库呢?原因之一就在于我们可以使jQuery代码在各种不同的浏览器和存在bug的浏览器上***运行。

 

  1. <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
  2.  
  3.         <script> 
  4.  
  5.             // Different ways to achieve the Document Ready event 
  6.  
  7.             // With jQuery 
  8.             $(document).ready(function(){ /* ... */}); 
  9.  
  10.             // Short jQuery 
  11.             $(function(){ /* ... */}); 
  12.  
  13.             // Without jQuery (doesn't work in older IE versions) 
  14.             document.addEventListener('DOMContentLoaded',function(){ 
  15.                 // Your code goes here 
  16.             }); 
  17.  
  18.             // The Trickshot (works everywhere): 
  19.  
  20.             r(function(){ 
  21.                 alert('DOM Ready!'); 
  22.             }) 
  23.  
  24.             function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} 
  25.  
  26.         </script> 

2.使用route。

 

  1. <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
  2.  
  3.         <script> 
  4.  
  5.             var route = { 
  6.                 _routes : {},    // The routes will be stored here 
  7.  
  8.                 add    : function(url, action){ 
  9.                     this._routes[url] = action; 
  10.                 }, 
  11.  
  12.                 run : function(){ 
  13.                     jQuery.each(this._routes, function(pattern){ 
  14.                         if(location.href.match(pattern)){ 
  15.                             // "this" points to the function to be executed 
  16.                             this(); 
  17.                         } 
  18.                     }); 
  19.                 } 
  20.             } 
  21.  
  22.             // Will execute only on this page: 
  23.             route.add('002.html', function(){ 
  24.                 alert('Hello there!'
  25.             }); 
  26.  
  27.             route.add('products.html', function(){ 
  28.                 alert("this won't be executed : ("
  29.             }); 
  30.  
  31.             // You can even use regex-es: 
  32.             route.add('.*.html', function(){ 
  33.                 alert('This is using a regex!'
  34.             }); 
  35.  
  36.             route.run(); 
  37.  
  38.         </script> 

3.使用JavaScript中的AND技巧。

使用&&操作符的特点是如果操作符左边的表达式是false,那么它就不会再判断操作符右边的表达式了。所以:

 

  1. // Instead of writing this: 
  2. if($('#elem').length){ 
  3.     // do something 
  4.  
  5. // You can write this: 
  6.  
  7. $('#elem').length && log("doing something"); 

4. is()方法比你想象的更为强大。

下面举几个例子,我们先写一个id为elem的div。js代码如下:

 

  1. // First, cache the element into a variable: 
  2. var elem = $('#elem'); 
  3.  
  4. // Is this a div? 
  5. elem.is('div') && log("it's a div"); 
  6.  
  7. // Does it have the bigbox class? 
  8. elem.is('.bigbox') && log("it has the bigbox class!"); 
  9.  
  10. // Is it visible? (we are hiding it in this example) 
  11. elem.is(':not(:visible)') && log("it is hidden!"); 
  12.  
  13. // Animating 
  14. elem.animate({'width':200},1); 
  15.  
  16. // is it animated? 
  17. elem.is(':animated') && log("it is animated!"); 

其中判断是否为动画我觉得非常不错。

5.判断你的网页一共有多少元素。

通过使用$(“*”).length();方法可以判断网页的元素数量。

 

  1. // How many elements does your page have? 
  2. log('This page has ' + $('*').length + ' elements!'); 

6.使用length()属性很笨重,下面我们使用exist()方法。

 

  1. / Old way 
  2. log($('#elem').length == 1 ? "exists!" : "doesn't exist!"); 
  3.  
  4. // Trickshot: 
  5.  
  6. jQuery.fn.exists = function(){ return this.length > 0; } 
  7.  
  8. log($('#elem').exists() ? "exists!" : "doesn't exist!"); 

7.jQuery方法$()实际上是拥有两个参数的,你知道第二个参数的作用吗?

 

  1. // Select an element. The second argument is context to limit the search 
  2. // You can use a selector, jQuery object or dom element 
  3.  
  4. $('li','#firstList').each(function(){ 
  5.     log($(this).html()); 
  6. }); 
  7.  
  8. log('-----'); 
  9.  
  10. // Create an element. The second argument is an 
  11. // object with jQuery methods to be called 
  12.  
  13. var div = $('<div>',{ 
  14.     "class""bigBlue"
  15.     "css": { 
  16.         "background-color":"purple" 
  17.     }, 
  18.     "width" : 20
  19.     "height"20
  20.     "animate" : {   // You can use any jQuery method as a property! 
  21.         "width"200
  22.         "height":50 
  23.     } 
  24. }); 
  25.  
  26. div.appendTo('#result'); 

8.使用jQuery我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接中,且确定打开方式。

这里用到了hostname属性。

 

  1. <ul id="links">  
  2.    <li><a href="007.html">The previous tip</a></li>  
  3.    <li><a href="./009.html">The next tip</a></li> 
  4.    <li><a href="http://www.google.com/">Google</a></li>  
  5. </ul> 
  6.  
  7. // Loop through all the links 
  8. $('#links a').each(function(){ 
  9.  
  10.     if(this.hostname != location.hostname){ 
  11.         // The link is external 
  12.         $(this).append('<img src="assets/img/external.png" />'
  13.                .attr('target','_blank'); 
  14.     } 
  15.  
  16. }); 

9.jQuery中的end()方法可以使你的jQuery链更加高效。

 

  1. <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> 
  2. // Here is how it is used: 
  3.  
  4. var breakfast = $('#meals .breakfast'); 
  5.  
  6. breakfast.find('.eggs').text('Yes'
  7.                       .end() // back to breakfast 
  8.                       .find('.toast').text('Yes'
  9.                       .end() 
  10.                       .find('.juice').toggleClass('juice coffee').text('Yes'); 
  11.  
  12. breakfast.find('li').each(function(){ 
  13.     log(this.className + ': ' + this.textContent) 
  14. }); 

10.也许你希望你的web 应用感觉更像原生的,那么你可以阻止contextmenu默认事件。

 

  1. <script> 
  2. // Prevent right clicking on this page 
  3. $(function(){ 
  4. $(document).on("contextmenu",function(e){ 
  5. e.preventDefault(); 
  6. }); 
  7. }); 
  8. </script> 

11.一些站点可能会使你的网页在一个bar下面,即我们所看到在下面的网页是iframe标签中的,我们可以这样解决。

 

  1. // Here is how it is used: 
  2.  
  3. if(window != window.top){ 
  4.     window.top.location = window.location; 
  5. else
  6.     alert('This page is not displayed in a frame. Open 011.html to see it in action.'); 

12.你的内联样式表并不是被设置为不可改变的,如下:

 

  1. // Make the stylesheet visible and editable 
  2. $('#regular-style-block').css({'display':'block''white-space':'pre'}) 
  3.                          .attr('contentEditable',true); 

这样即可改变内联样式了。

13.有时候我们不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:

 

  1. <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> 
  2.  
  3.      <script> 
  4.             // Prevent text from being selected 
  5.             $(function(){ 
  6.                 $('p.descr').attr('unselectable''on'
  7.                            .css('user-select''none'
  8.                            .on('selectstart'false); 
  9.           }); 
  10.      </script> 

这样,内容就不能被选择啦。

14.从CDN中引入jQuery,这样的方法可以提高我们网站的性能,并且引入***的版本也是一个不错的主意。

下面会介绍四种不同的方法。

 

  1. <!-- Case 1 - requesting jQuery from the official CDN --> 
  2. <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
  3. <!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) --> 
  4. <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> --> 
  5. <!-- Case 3 - requesting the latest minor 1.8.x version (only cached for an hour) --> 
  6. <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script> --> 
  7. <!-- Case 4 - requesting the absolute latest jQuery version (use with caution) --> 
  8. <!-- <script src="http://code.jquery.com/jquery.min.js"></script> --> 

15.保证最小的DOM操作。

我们知道js操作DOM是非常浪费资源的,我们可以看看下面的例子。

 

  1. CODE 
  2. // Bad 
  3. //var elem = $('#elem'); 
  4. //for(var i = 0; i < 100; i++){ 
  5. //    elem.append('<li>element '+i+'</li>'); 
  6. //} 
  7.  
  8. // Good 
  9. var elem = $('#elem'), 
  10.     arr = []; 
  11.  
  12. for(var i = 0; i < 100; i++){ 
  13.     arr.push('<li>element '+i+'</li>'); 
  14.  
  15. elem.append(arr.join('')); 

16.更方便的分解URL。

也许你会使用正则表达式来解析URL,但这绝对不是一种好的方法,我们可以借用a标签来实现它。

 

  1. // You want to parse this address into parts: 
  2. var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments'
  3.  
  4. // The trickshot: 
  5. var a = $('<a>',{ href: url }); 
  6.  
  7. log('Host name: ' + a.prop('hostname')); 
  8. log('Path: ' + a.prop('pathname')); 
  9. log('Query: ' + a.prop('search')); 
  10. log('Protocol: ' + a.prop('protocol')); 
  11. log('Hash: ' + a.prop('hash')); 

17.不要害怕使用vanilla.js。

 

  1. // Print the IDs of all LI items 
  2. $('#colors li').each(function(){ 
  3.  
  4.     // Access the ID directly, instead 
  5.     // of using jQuery's $(this).attr('id') 
  6.  
  7.     log(this.id); 
  8.  
  9. }); 

 

18.***化你的选择器

 

  1. // Let's try some benchmarks! 
  2.  
  3. var iterations = 10000, i; 
  4.  
  5. timer('Fancy'); 
  6.  
  7. for(i=0; i < iterations; i++){ 
  8.     // This falls back to a SLOW JavaScript dom traversal 
  9.     $('#peanutButter div:first'); 
  10.  
  11. timer_result('Fancy'); 
  12.  
  13. timer('Parent-child'); 
  14.  
  15. for(i=0; i < iterations; i++){ 
  16.     // Better, but still slow 
  17.     $('#peanutButter div'); 
  18.  
  19. timer_result('Parent-child'); 
  20.  
  21. timer('Parent-child by class'); 
  22.  
  23. for(i=0; i < iterations; i++){ 
  24.     // Some browsers are a bit faster on this one 
  25.     $('#peanutButter .jellyTime'

19.缓存你的selector。

 

  1. // Bad: 
  2. // $('#pancakes li').eq(0).remove(); 
  3. // $('#pancakes li').eq(1).remove(); 
  4. // $('#pancakes li').eq(2).remove(); 
  5.  
  6. // Good: 
  7. var pancakes = $('#pancakes li'); 
  8.  
  9. pancakes.eq(0).remove(); 
  10. pancakes.eq(1).remove(); 
  11. pancakes.eq(2).remove(); 
  12.  
  13. // Alternatively: 
  14. // pancakes.eq(0).remove().end() 
  15. //           .eq(1).remove().end() 
  16. //           .eq(2).remove().end(); 

20.对于重复的函数只定义一次

如果你追求代码的更高性能,那么当你设置事件监听程序时必须小心,只定义一次函数然后把它的名字作为事件处理程序传递是不错的方法。

 

  1. $(document).ready(function(){ 
  2.     function showMenu(){ 
  3.         alert('Showing menu!'); 
  4.         // Doing something complex here 
  5.     } 
  6.  
  7.     $('#menuButton').click(showMenu); 
  8.     $('#menuLink').click(showMenu); 
  9.  
  10. }); 

21.像对待数组一样地对待jQuery对象

由于jQuery对象有index值和长度,所以这意味着我们可以把对象当作普通的数组对待。这样也会有更好地性能。

 

  1. var arr = $('li'), 
  2.     iterations = 100000
  3.  
  4. timer('Native Loop'); 
  5.  
  6. for(var z=0;z<iterations;z++){ 
  7.  
  8.     var length = arr.length; 
  9.     for(var i=0; i < length; i++){ 
  10.       arr[i]; 
  11.     } 
  12. timer_result('Native Loop'); 
  13.  
  14. timer('jQuery Each'); 
  15.  
  16. for(z=0;z<iterations;z++){ 
  17.  
  18.     arr.each(function(i, val) { 
  19.       this
  20.     }); 
  21. timer_result('jQuery Each'); 

22.当做复杂的修改时要分离元素。

修改一个dom元素要求网页重绘,这个代价是高昂的,所以如果你想要再提高性能,就可以尝试着当对一个元素进行大量修改时先从页面中分离这个元素,修改完之后再添加到页面。

 

  1. // Modifying in place 
  2. var elem = $('#elem'); 
  3.  
  4. timer('In place'); 
  5.  
  6. for(i=0; i &lt; iterations; i++){ 
  7.  
  8.     elem.width(Math.round(100*Math.random())); 
  9.     elem.height(Math.round(100*Math.random())); 
  10.  
  11.  
  12. timer_result('In place'); 
  13.  
  14. var parent = elem.parent(); 
  15.  
  16. // Detaching first 
  17. timer('Detached'); 
  18.  
  19. elem.detach(); 
  20.  
  21. for(i=0; i &lt; iterations; i++){ 
  22.  
  23.     elem.width(Math.round(100*Math.random())); 
  24.     elem.height(Math.round(100*Math.random())); 
  25.  
  26.  
  27. elem.appendTo(parent); 
  28.  
  29. timer_result('Detached'); 

23.不要一直等待load事件。

我们已经习惯了把我们所有的代码都放在ready的事件处理程序中,但是,如果你的html页面很庞大,decument ready恐怕会被延迟了,所以对于一些我们不希望ready后才可以触发的事件可以放在html的head元素中。

 

  1. <script> 
  2.  
  3.             // jQuery is loaded at this point. We can use 
  4.             // event delegation right away to bind events 
  5.             // even before $(document).ready: 
  6.  
  7.             $(document).on('click''#clickMe', function(){ 
  8.                 alert('Hit view source and see how this is made'); 
  9.             }); 
  10.  
  11.             $(document).ready(function(){ 
  12.  
  13.                 // This is where you would usually bind event handlers, 
  14.                 // but as we are using delegation, there is no need to. 
  15.  
  16.                 // $('#clickMe').click(function(){ alert('Hey!'); }); 
  17.             }); 
  18.  
  19.             // Note: You should place your script tags at the bottom of the page. 
  20.             // I have included them in the head only to demonstrate that we can bind 
  21.             // events before document ready and before the elements are created. 
  22.  
  23. </script> 

24.当使用js给多个元素添加样式时更好的做法是创建一个style元素。

我们之前提到过,操作dom是非常慢的,所以当添加多个元素的样式时创建一个style元素并添加到document中是更好的做法。

 

  1. <ul id="testList"
  2.  <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> 
  3.  </ul> 
  4.  
  5. var style = $('<style>'); 
  6.  
  7. // Try commenting out this line, or change the color: 
  8. style.text('#testList li{ color:red;}'); 
  9.  
  10. // Placing it before the result section so it affects the elements 
  11. style.prependTo('#result'); 

25.给html元素分配一个名为JS的class。

现代的web apps非常的依赖js,这里的一个技巧就是只有当js可用时才能显示特定的元素。看下面的代码。

 

  1. $(document).ready(function(){ 
  2.     $('html').addClass('JS'); 
  3. }); 
  4.  
  5.   html.JS #message { display:block; } 
  6.  #message {display:none;} 

这样,只有js可用的时候id为message的元素才会显示;如果不支持js,则该元素不会显示。

26.监听不存在的元素上的事件。

jQuery拥有一个先进的事件处理机制,通过on()方法可以监听还不存在的事件。 这是因为on方法可以传递一个元素的子元素选择器作为参数。看下面的例子:

 

  1. <ul id="testList"> <li>Old</li> <li>Old</li> <li>Old</li> <li>Old</li> </ul> 
  2.  
  3. var list = $('#testList'); 
  4.  
  5. // Binding an event on the list, but listening for events on the li items: 
  6. list.on('click','li',function(){ 
  7.     $(this).remove(); 
  8. }); 
  9.  
  10. // This allows us to create li elements at a later time, 
  11. // while keeping the functionality in the event listener 
  12.  
  13. list.append('<li>New item (click me!)</li>'); 

这样,即使li是后创建的,也可以通过on()方法来监听。

27.只使用一次事件监听。

有时,我们只需要绑定只运行一次的事件处理程序。那么one()方法是一个不错的选择,通过它你就可以高枕无忧了。

 

  1. <button id="press">Press me!</ul> 
  2. var press = $('#press'); 
  3.  
  4. // There is a method that does exactly that, the one(): 
  5. press.one('click',function(){ 
  6.     alert('This alert will pop up only once'); 
  7. }); 
  8.  
  9. // What this method does, is call on() behind the scenes, 
  10. // with a 1 as the last argument: 
  11. // press.on('click',null,null,function(){alert('I am the one and only!');}, 1); 

28.模拟触发事件。

我们可以通过使用trigger模拟触发一个click事件。

 

  1. <button id="press">Press me!</ul> 
  2. var press = $('#press'); 
  3.  
  4. // Just a regular event listener: 
  5. press.on('click',function(e, how){ 
  6.     how = how || ''
  7.     alert('The buton was clicked ' + how + '!'); 
  8. }); 
  9.  
  10. // Trigger the click event 
  11. press.trigger('click'); 
  12.  
  13. // Trigger it with an argument 
  14. press.trigger('click',['fast']); 

29.使用触摸事件。

使用触摸事件和相关的鼠标事件并没有太多不同,但是你得有一个方便的移动设备来测试会更好。看下面这个例子。

 

  1. // Define some variables 
  2. var ball = $('&lt;div id="ball"&gt;&lt;/div&gt;').appendTo('body'), 
  3. startPosition = {}, elementPosition = {}; 
  4.  
  5. // Listen for mouse and touch events 
  6. ball.on('mousedown touchstart',function(e){ 
  7.     e.preventDefault(); 
  8.  
  9.     // Normalizing the touch event object 
  10.     e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; 
  11.  
  12.     // Recording current positions 
  13.     startPosition = {x: e.pageX, y: e.pageY}; 
  14.     elementPosition = {x: ball.offset().left, y: ball.offset().top}; 
  15.  
  16.     // These event listeners will be removed later 
  17.     ball.on('mousemove.rem touchmove.rem',function(e){ 
  18.         e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; 
  19.  
  20.         ball.css({ 
  21.             top:elementPosition.y + (e.pageY - startPosition.y), 
  22.             left: elementPosition.x + (e.pageX - startPosition.x), 
  23.         }); 
  24.  
  25.     }); 
  26. }); 
  27.  
  28. ball.on('mouseup touchend',function(){ 
  29.     // Removing the heavy *move listeners 
  30.     ball.off('.rem'); 
  31. }); 

30.更好地使用on()/off()方法。

在jQuery1.7版本时对事件处理进行了简化,看看下面的例子吧。

 

  1. <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> 
  2.  
  3. // Lets cache some selectors 
  4.  
  5. var button1 = $('#button1'), 
  6.     button2 = $('#button2'), 
  7.     button3 = $('#button3'), 
  8.     button4 = $('#button4'), 
  9.     clear = $('#clear'), 
  10.     holder = $('#holder'); 
  11.  
  12. // Case 1: Direct event handling 
  13. button1.on('click',function(){ 
  14.     log('Click'); 
  15. }); 
  16.  
  17. // Case 2: Direct event handling of multiple events 
  18. button2.on('mouseenter mouseleave',function(){ 
  19.     log('In/Out'); 
  20. }); 
  21.  
  22. // Case 3: Data passing 
  23. button3.on('click', Math.round(Math.random()*20), function(e){ 
  24.  
  25.     // This will print the same number over and over again, 
  26.     // as the random number above is generated only once: 
  27.     log('Random number: ' + e.data); 
  28.  
  29. }); 
  30.  
  31. // Case 4: Events with a namespace 
  32. button4.on('click.temp', function(e){ 
  33.     log('Temp event!'); 
  34. }); 
  35.  
  36. button2.on('click.temp', function(e){ 
  37.     log('Temp event!'); 
  38. }); 
  39.  
  40. // Case 5: Using event delegation 
  41. $('#holder').on('click''#clear', function(){ 
  42.     log.clear(); 
  43. }); 
  44.  
  45. // Case 6: Passing an event map 
  46. var t; // timer 
  47.  
  48. clear.on({ 
  49.  
  50.     'mousedown':function(){ 
  51.  
  52.         t = new Date(); 
  53.  
  54.     }, 
  55.  
  56.     'mouseup':function(){ 
  57.  
  58.         if(new Date() - t &gt; 1000){ 
  59.  
  60.             // The button has been held pressed 
  61.             // for more than a second. Turn off 
  62.             // the temp events 
  63.  
  64.             $('button').off('.temp'); 
  65.             alert('The .temp events were cleared!'); 
  66.         } 
  67.  
  68.     } 
  69. }); 

31.更快地阻止默认事件行为。

我们知道js中可以使用preventDefault()方法来阻止默认行为,但是jQuery对此提供了更简单的方法。如下:

  1. <a href="http://google.com/" id="goToGoogle">Go To Google</a> $('#goToGoogle').click(false); 

32.使用event.result链接多个事件处理程序。

对一个元素绑定多个事件处理程序并不常见,而使用event.result更可以将多个事件处理程序联系起来。看下面的例子。

 

  1. <button id="press">点击</button> 
  2.  <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
  3.  <script> 
  4.  
  5. var press = $('#press'); 
  6. press.on('click',function(){ 
  7.     return 'Hip'
  8. }); 
  9.  
  10. // The second event listener has access 
  11. // to what was returned from the first 
  12.  
  13. press.on('click',function(e){ 
  14.     console.log(e.result + ' Hop!'); 
  15. }); 
  16.  </script> 

这样,控制台会输出Hip Hop!

33.创建你自己习惯的事件。

你可以使用on()方法创建自己喜欢的事件名称,然后通过trigger来触发。举例如下:

 

  1. <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> 
  2.      <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
  3.  
  4.      <script> 
  5.  
  6. var button1 = $('#button1'), 
  7.     button2 = $('#button2'), 
  8.     button3 = $('#button3'), 
  9.     clear = $('#clear'), 
  10.     div = $('#eventDiv'); 
  11.  
  12. div.on({ 
  13.     jump : function(){ 
  14.         alert('Jumped!'); 
  15.     }, 
  16.  
  17.     punch : function(e,data){ 
  18.         alert('Punched '+data+'!'); 
  19.     }, 
  20.  
  21.     click : function(){ 
  22.         alert('Simulated click!'); 
  23.     } 
  24.  
  25. }); 
  26.  
  27. button1.click(function(){ 
  28.     div.trigger('jump'); 
  29. }); 
  30.  
  31. button2.click(function(){ 
  32.     // Pass data along with the event 
  33.     div.trigger('punch',['hard']); 
  34. }); 
  35.  
  36. button3.click(function(){ 
  37.     div.trigger('click'); 
  38. }); 
  39.  
  40. clear.click(function(){ 
  41.     //some clear code 
  42. }); 
  43.  
  44.      </script> 

34.在下载文件旁显示文件大小。

你知道如何在不下载一个文件的情况下通过发送一个ajax请求头得到一个文件的大小吗? 使用jQuery就很容易。

 

  1. <a href="001.html" class="fetchSize">First Trickshot</a> <br />  
  2. <a href="034.html" class="fetchSize">This Trickshot</a> <br />  
  3. <a href="assets/img/ball.png" class="fetchSize">Ball.png</a> <br /> 
  4.  
  5. // Loop all .fetchSize links 
  6. $('a.fetchSize').each(function(){ 
  7.  
  8.     // Issue an AJAX HEAD request for each one 
  9.     var link = this
  10.  
  11.     $.ajax({ 
  12.         type        : 'HEAD'
  13.         url            : link.href, 
  14.         complete    : function(xhr){ 
  15.  
  16.             // Append the filesize to each 
  17.             $(link).append(' (' + humanize(xhr.getResponseHeader('Content-Length')) + ')'); 
  18.  
  19.         } 
  20.     }); 
  21.  
  22. }); 
  23.  
  24. function humanize(size){ 
  25.     var units = ['bytes','KB','MB','GB','TB','PB']; 
  26.  
  27.     var ord = Math.floor( Math.log(size) / Math.log(1024) ); 
  28.     ord = Math.min( Math.max(0,ord), units.length-1); 
  29.  
  30.     var s = Math.round((size / Math.pow(1024,ord))*100)/100
  31.     return s + ' ' + units[ord]; 

注意:这个例子如何我们直接使用浏览器是没法得到的,必须使用本地的web服务器打开运行才可以。

35.使用延迟简化你的Ajax请求

延迟(deferreds)是一个强大的工具。jQuery对于每一个Ajax请求都会返回一个deferred对象。 deferred.done()方法接受一个或多个参数,所有这些都参数可以是一个单一的函数或一个函数数组。当Deferred(延迟)解决时,doneCallbacks被调用。回调是依照他们添加的顺序执行。一旦deferred.done()返回Deferred(延迟)对象,Deferred(延迟)可以链接其它的延迟对象,包括增加额外的.done()方法。下面这样就会使你的代码更易读:

 

  1. // This is equivalent to passing a callback as the 
  2. // second argument (executed on success): 
  3.  
  4. $.get('assets/misc/1.json').done(function(r){ 
  5.     log(r.message); 
  6. }); 
  7.  
  8. // Requesting a file that does not exist. This will trigger 
  9. // the failure response. To handle it, you would normally have to 
  10. // use the full $.ajax method and pass it as a failure callback, 
  11. // but with deferreds you can can simply use the fail method: 
  12.  
  13. $.get('assets/misc/non-existing.json').fail(function(r){ 
  14.     log('Oops! The second ajax request was "' + r.statusText + '" (error ' + r.status + ')!'); 
  15. }); 

36.平行的运行多个Ajax请求。

当我们需要发送多个Ajax请求是,相反于等待一个发送结束再发送下一个,我们可以平行地发送来加速Ajax请求发送。

 

  1. // The trick is in the $.when() function: 
  2.  
  3. $.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){ 
  4.     log(r1[0].message + " " + r2[0].message); 
  5. }); 

37.通过jQuery获得ip

我们不仅可以在电脑上ping到一个网站的ip,也可以通过jQuery得到。

 

  1. $.get('http://jsonip.com/', function(r){ log(r.ip); }); 
  2.  
  3. // For older browsers, which don't support CORS 
  4. // $.getJSON('http://jsonip.com/?callback=?', function(r){ log(r.ip); }); 

38.使用最简单的ajax请求

jQuery(使用ajax)提供了一个速记的方法来快速下载内容并添加在一个元素中。

 

  1. <p class="content"></p> <p class="content"></p> 
  2.  
  3. var contentDivs = $('.content'); 
  4.  
  5. // Fetch the contents of a text file: 
  6. contentDivs.eq(0).load('1.txt'); 
  7.  
  8. // Fetch the contents of a HTML file, and display a specific element: 
  9. contentDivs.eq(1).load('1.html #header'); 

39.序列化对象

jQuery提供了一个方法序列化表单值和一般的对象成为URL编码文本字符串。这样,我们就可以把序列化的值传给ajax()作为url的参数,轻松使用ajax()提交表单了。

 

  1. <form action=""
  2. First name: <input type="text" name="FirstName" value="Bill" /><br /> 
  3. Last name: <input type="text" name="LastName" value="Gates" /><br /> 
  4. </form> 
  5.  
  6. // Turn all form fields into a URL friendly key/value string. 
  7. // This can be passed as argument of AJAX requests, or URLs. 
  8.  
  9. $(document).ready(function(){ 
  10.     console.log($("form").serialize()); // FirstName=Bill&LastName=Gates 
  11. }); 
  12.  
  13. // You can also encode your own objects with the $.param method: 
  14. log($.param({'pet':'cat''name':'snowbell'})); 

 

 

责任编辑:张燕妮 来源: 918之初
相关推荐

2009-12-30 09:09:13

Web表单

2011-06-16 12:43:22

jQuery

2023-04-26 00:34:36

Python技巧程序员

2021-11-15 10:02:16

Python命令技巧

2021-01-31 23:56:49

JavaScript开发代码

2018-12-07 10:30:50

盘点CSS前端

2018-05-14 17:33:28

学习编程课程

2012-10-08 09:21:49

jQuery Mobi

2010-11-30 09:06:28

Visual Stud

2010-06-18 09:17:51

jQuery

2020-11-11 08:22:40

前端开发JavaScript

2009-06-10 21:58:51

Javascript常

2011-07-07 17:24:28

PHP

2011-07-07 17:27:54

PHP

2018-05-10 16:02:48

Android程序赠工具

2023-09-04 15:52:07

2017-03-07 09:15:08

iOS技巧开发

2021-12-11 23:13:16

Python语言技巧

2021-10-06 15:58:26

Python工具代码

2015-08-19 09:15:11

C#程序员实用代码
点赞
收藏

51CTO技术栈公众号