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

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

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

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

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

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

  1. <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  2. <script>
  3. //DifferentwaystoachievetheDocumentReadyevent
  4. //WithjQuery
  5. $(document).ready(function(){/*...*/});
  6. //ShortjQuery
  7. $(function(){/*...*/});
  8. //WithoutjQuery(doesn'tworkinolderIEversions)
  9. document.addEventListener('DOMContentLoaded',function(){
  10. //Yourcodegoeshere
  11. });
  12. //TheTrickshot(workseverywhere):
  13. r(function(){
  14. alert('DOMReady!');
  15. })
  16. functionr(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
  17. </script>

2.使用route。

  1. <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  2. <script>
  3. varroute={
  4. _routes:{},//Therouteswillbestoredhere
  5. add:function(url,action){
  6. this._routes[url]=action;
  7. },
  8. run:function(){
  9. jQuery.each(this._routes,function(pattern){
  10. if(location.href.match(pattern)){
  11. //"this"pointstothefunctiontobeexecuted
  12. this();
  13. }
  14. });
  15. }
  16. }
  17. //Willexecuteonlyonthispage:
  18. route.add('002.html',function(){
  19. alert('Hellothere!')
  20. });
  21. route.add('products.html',function(){
  22. alert("thiswon'tbeexecuted:(")
  23. });
  24. //Youcanevenuseregex-es:
  25. route.add('.*.html',function(){
  26. alert('Thisisusingaregex!')
  27. });
  28. route.run();
  29. </script>

3.使用JavaScript中的AND技巧

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

  1. //Insteadofwritingthis:
  2. if($('#elem').length){
  3. //dosomething
  4. }
  5. //Youcanwritethis:
  6. $('#elem').length&&log("doingsomething");

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

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

  1. //First,cachetheelementintoavariable:
  2. varelem=$('#elem');
  3. //Isthisadiv?
  4. elem.is('div')&&log("it'sadiv");
  5. //Doesithavethebigboxclass?
  6. elem.is('.bigbox')&&log("ithasthebigboxclass!");
  7. //Isitvisible?(wearehidingitinthisexample)
  8. elem.is(':not(:visible)')&&log("itishidden!");
  9. //Animating
  10. elem.animate({'width':200},1);
  11. //isitanimated?
  12. elem.is(':animated')&&log("itisanimated!");

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

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

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

  1. //Howmanyelementsdoesyourpagehave?
  2. log('Thispagehas'+$('*').length+'elements!');

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

  1. /Oldway
  2. log($('#elem').length==1?"exists!":"doesn'texist!");
  3. //Trickshot:
  4. jQuery.fn.exists=function(){returnthis.length>0;}
  5. log($('#elem').exists()?"exists!":"doesn'texist!");

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

  1. //Selectanelement.Thesecondargumentiscontexttolimitthesearch
  2. //Youcanuseaselector,jQueryobjectordomelement
  3. $('li','#firstList').each(function(){
  4. log($(this).html());
  5. });
  6. log('-----');
  7. //Createanelement.Thesecondargumentisan
  8. //objectwithjQuerymethodstobecalled
  9. vardiv=$('<div>',{
  10. "class":"bigBlue",
  11. "css":{
  12. "background-color":"purple"
  13. },
  14. "width":20,
  15. "height":20,
  16. "animate":{//YoucanuseanyjQuerymethodasaproperty!
  17. "width":200,
  18. "height":50
  19. }
  20. });
  21. div.appendTo('#result');

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

这里用到了hostname属性。

  1. <ulid="links">
  2. <li><ahref="007.html">Theprevioustip</a></li>
  3. <li><ahref="./009.html">Thenexttip</a></li>
  4. <li><ahref="http://www.google.com/">Google</a></li>
  5. </ul>
  6. //Loopthroughallthelinks
  7. $('#linksa').each(function(){
  8. if(this.hostname!=location.hostname){
  9. //Thelinkisexternal
  10. $(this).append('<imgsrc="assets/img/external.png"/>')
  11. .attr('target','_blank');
  12. }
  13. });

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

  1. <ulid="meals"><li><ulclass="breakfast"><liclass="eggs">No</li><liclass="toast">No</li><liclass="juice">No</li></ul></li></ul>
  2. //Hereishowitisused:
  3. varbreakfast=$('#meals.breakfast');
  4. breakfast.find('.eggs').text('Yes')
  5. .end()//backtobreakfast
  6. .find('.toast').text('Yes')
  7. .end()
  8. .find('.juice').toggleClass('juicecoffee').text('Yes');
  9. breakfast.find('li').each(function(){
  10. log(this.className+':'+this.textContent)
  11. });

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

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

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

  1. //Hereishowitisused:
  2. if(window!=window.top){
  3. window.top.location=window.location;
  4. }
  5. else{
  6. alert('Thispageisnotdisplayedinaframe.Open011.htmltoseeitinaction.');
  7. }

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

  1. //Makethestylesheetvisibleandeditable
  2. $('#regular-style-block').css({'display':'block','white-space':'pre'})
  3. .attr('contentEditable',true);

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

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

  1. <pclass="descr">Incertainsituationsyoumightwanttopreventtextonthepagefrombeingselectable.Tryselectingthistextandhitviewsourcetoseehowitisdone.</p>
  2. <script>
  3. //Preventtextfrombeingselected
  4. $(function(){
  5. $('p.descr').attr('unselectable','on')
  6. .css('user-select','none')
  7. .on('selectstart',false);
  8. });
  9. </script>

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

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

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

  1. <!--Case1-requestingjQueryfromtheofficialCDN-->
  2. <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  3. <!--Case2-requestingjQueryfromGoogle'sCDN(noticetheprotocol)-->
  4. <!--<scriptsrc="//gapis.geekzu.org/ajax/ajax/libs/jquery/1.10.2/jquery.min.js"></script>-->
  5. <!--Case3-requestingthelatestminor1.8.xversion(onlycachedforanhour)-->
  6. <!--<scriptsrc="//gapis.geekzu.org/ajax/ajax/libs/jquery/1.10/jquery.min.js"></script>-->
  7. <!--Case4-requestingtheabsolutelatestjQueryversion(usewithcaution)-->
  8. <!--<scriptsrc="http://code.jquery.com/jquery.min.js"></script>-->

15.保证最小的DOM操作。

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

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

16.更方便的分解URL。

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

  1. //Youwanttoparsethisaddressintoparts:
  2. varurl='http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';
  3. //Thetrickshot:
  4. vara=$('<a>',{href:url});
  5. log('Hostname:'+a.prop('hostname'));
  6. log('Path:'+a.prop('pathname'));
  7. log('Query:'+a.prop('search'));
  8. log('Protocol:'+a.prop('protocol'));
  9. log('Hash:'+a.prop('hash'));

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

  1. //PrinttheIDsofallLIitems
  2. $('#colorsli').each(function(){
  3. //AccesstheIDdirectly,instead
  4. //ofusingjQuery's$(this).attr('id')
  5. log(this.id);
  6. });

18.***化你的选择器

  1. //Let'strysomebenchmarks!
  2. variterations=10000,i;
  3. timer('Fancy');
  4. for(i=0;i<iterations;i++){
  5. //ThisfallsbacktoaSLOWJavaScriptdomtraversal
  6. $('#peanutButterdiv:first');
  7. }
  8. timer_result('Fancy');
  9. timer('Parent-child');
  10. for(i=0;i<iterations;i++){
  11. //Better,butstillslow
  12. $('#peanutButterdiv');
  13. }
  14. timer_result('Parent-child');
  15. timer('Parent-childbyclass');
  16. for(i=0;i<iterations;i++){
  17. //Somebrowsersareabitfasteronthisone
  18. $('#peanutButter.jellyTime')

19.缓存你的selector。

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

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

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

  1. $(document).ready(function(){
  2. functionshowMenu(){
  3. alert('Showingmenu!');
  4. //Doingsomethingcomplexhere
  5. }
  6. $('#menuButton').click(showMenu);
  7. $('#menuLink').click(showMenu);
  8. });

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

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

  1. vararr=$('li'),
  2. iterations=100000;
  3. timer('NativeLoop');
  4. for(varz=0;z<iterations;z++){
  5. varlength=arr.length;
  6. for(vari=0;i<length;i++){
  7. arr[i];
  8. }
  9. }
  10. timer_result('NativeLoop');
  11. timer('jQueryEach');
  12. for(z=0;z<iterations;z++){
  13. arr.each(function(i,val){
  14. this;
  15. });
  16. }
  17. timer_result('jQueryEach');

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

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

  1. //Modifyinginplace
  2. varelem=$('#elem');
  3. timer('Inplace');
  4. for(i=0;i&lt;iterations;i++){
  5. elem.width(Math.round(100*Math.random()));
  6. elem.height(Math.round(100*Math.random()));
  7. }
  8. timer_result('Inplace');
  9. varparent=elem.parent();
  10. //Detachingfirst
  11. timer('Detached');
  12. elem.detach();
  13. for(i=0;i&lt;iterations;i++){
  14. elem.width(Math.round(100*Math.random()));
  15. elem.height(Math.round(100*Math.random()));
  16. }
  17. elem.appendTo(parent);
  18. timer_result('Detached');

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

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

  1. <script>
  2. //jQueryisloadedatthispoint.Wecanuse
  3. //eventdelegationrightawaytobindevents
  4. //evenbefore$(document).ready:
  5. $(document).on('click','#clickMe',function(){
  6. alert('Hitviewsourceandseehowthisismade');
  7. });
  8. $(document).ready(function(){
  9. //Thisiswhereyouwouldusuallybindeventhandlers,
  10. //butasweareusingdelegation,thereisnoneedto.
  11. //$('#clickMe').click(function(){alert('Hey!');});
  12. });
  13. //Note:Youshouldplaceyourscripttagsatthebottomofthepage.
  14. //Ihaveincludedthemintheheadonlytodemonstratethatwecanbind
  15. //eventsbeforedocumentreadyandbeforetheelementsarecreated.
  16. </script>

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

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

  1. <ulid="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. varstyle=$('<style>');
  5. //Trycommentingoutthisline,orchangethecolor:
  6. style.text('#testListli{color:red;}');
  7. //Placingitbeforetheresultsectionsoitaffectstheelements
  8. style.prependTo('#result');

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

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

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

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

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

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

  1. <ulid="testList"><li>Old</li><li>Old</li><li>Old</li><li>Old</li></ul>
  2. varlist=$('#testList');
  3. //Bindinganeventonthelist,butlisteningforeventsontheliitems:
  4. list.on('click','li',function(){
  5. $(this).remove();
  6. });
  7. //Thisallowsustocreatelielementsatalatertime,
  8. //whilekeepingthefunctionalityintheeventlistener
  9. list.append('<li>Newitem(clickme!)</li>');

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

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

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

  1. <buttonid="press">Pressme!</ul>
  2. varpress=$('#press');
  3. //Thereisamethodthatdoesexactlythat,theone():
  4. press.one('click',function(){
  5. alert('Thisalertwillpopuponlyonce');
  6. });
  7. //Whatthismethoddoes,iscallon()behindthescenes,
  8. //witha1asthelastargument:
  9. //press.on('click',null,null,function(){alert('Iamtheoneandonly!');},1);

28.模拟触发事件。

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

  1. <buttonid="press">Pressme!</ul>
  2. varpress=$('#press');
  3. //Justaregulareventlistener:
  4. press.on('click',function(e,how){
  5. how=how||'';
  6. alert('Thebutonwasclicked'+how+'!');
  7. });
  8. //Triggertheclickevent
  9. press.trigger('click');
  10. //Triggeritwithanargument
  11. press.trigger('click',['fast']);

29.使用触摸事件。

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

  1. //Definesomevariables
  2. varball=$('&lt;divid="ball"&gt;&lt;/div&gt;').appendTo('body'),
  3. startPosition={},elementPosition={};
  4. //Listenformouseandtouchevents
  5. ball.on('mousedowntouchstart',function(e){
  6. e.preventDefault();
  7. //Normalizingthetoucheventobject
  8. e=(e.originalEvent.touches)?e.originalEvent.touches[0]:e;
  9. //Recordingcurrentpositions
  10. startPosition={x:e.pageX,y:e.pageY};
  11. elementPosition={x:ball.offset().left,y:ball.offset().top};
  12. //Theseeventlistenerswillberemovedlater
  13. ball.on('mousemove.remtouchmove.rem',function(e){
  14. e=(e.originalEvent.touches)?e.originalEvent.touches[0]:e;
  15. ball.css({
  16. top:elementPosition.y+(e.pageY-startPosition.y),
  17. left:elementPosition.x+(e.pageX-startPosition.x),
  18. });
  19. });
  20. });
  21. ball.on('mouseuptouchend',function(){
  22. //Removingtheheavy*movelisteners
  23. ball.off('.rem');
  24. });

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

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

  1. <divid="holder"><buttonid="button1">1</button><buttonid="button2">2</button><buttonid="button3">3</button><buttonid="button4">4</button><buttonid="clear"style="float:right;">Clear</button></div>
  2. //Letscachesomeselectors
  3. varbutton1=$('#button1'),
  4. button2=$('#button2'),
  5. button3=$('#button3'),
  6. button4=$('#button4'),
  7. clear=$('#clear'),
  8. holder=$('#holder');
  9. //Case1:Directeventhandling
  10. button1.on('click',function(){
  11. log('Click');
  12. });
  13. //Case2:Directeventhandlingofmultipleevents
  14. button2.on('mouseentermouseleave',function(){
  15. log('In/Out');
  16. });
  17. //Case3:Datapassing
  18. button3.on('click',Math.round(Math.random()*20),function(e){
  19. //Thiswillprintthesamenumberoverandoveragain,
  20. //astherandomnumberaboveisgeneratedonlyonce:
  21. log('Randomnumber:'+e.data);
  22. });
  23. //Case4:Eventswithanamespace
  24. button4.on('click.temp',function(e){
  25. log('Tempevent!');
  26. });
  27. button2.on('click.temp',function(e){
  28. log('Tempevent!');
  29. });
  30. //Case5:Usingeventdelegation
  31. $('#holder').on('click','#clear',function(){
  32. log.clear();
  33. });
  34. //Case6:Passinganeventmap
  35. vart;//timer
  36. clear.on({
  37. 'mousedown':function(){
  38. t=newDate();
  39. },
  40. 'mouseup':function(){
  41. if(newDate()-t&gt;1000){
  42. //Thebuttonhasbeenheldpressed
  43. //formorethanasecond.Turnoff
  44. //thetempevents
  45. $('button').off('.temp');
  46. alert('The.tempeventswerecleared!');
  47. }
  48. }
  49. });

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

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

  1. <ahref="http://google.com/"id="goToGoogle">GoToGoogle</a>$('#goToGoogle').click(false);

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

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

  1. <buttonid="press">点击</button>
  2. <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  3. <script>
  4. varpress=$('#press');
  5. press.on('click',function(){
  6. return'Hip';
  7. });
  8. //Thesecondeventlistenerhasaccess
  9. //towhatwasreturnedfromthefirst
  10. press.on('click',function(e){
  11. console.log(e.result+'Hop!');
  12. });
  13. </script>

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

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

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

  1. <buttonid="button1">Jump</button><buttonid="button2">Punch</button><buttonid="button3">Click</button><buttonid="clear"style="float:right;">Clear</button><divid="eventDiv"></div>
  2. <scriptsrc="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  3. <script>
  4. varbutton1=$('#button1'),
  5. button2=$('#button2'),
  6. button3=$('#button3'),
  7. clear=$('#clear'),
  8. div=$('#eventDiv');
  9. div.on({
  10. jump:function(){
  11. alert('Jumped!');
  12. },
  13. punch:function(e,data){
  14. alert('Punched'+data+'!');
  15. },
  16. click:function(){
  17. alert('Simulatedclick!');
  18. }
  19. });
  20. button1.click(function(){
  21. div.trigger('jump');
  22. });
  23. button2.click(function(){
  24. //Passdataalongwiththeevent
  25. div.trigger('punch',['hard']);
  26. });
  27. button3.click(function(){
  28. div.trigger('click');
  29. });
  30. clear.click(function(){
  31. //someclearcode
  32. });
  33. </script>

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

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

  1. <ahref="001.html"class="fetchSize">FirstTrickshot</a><br/>
  2. <ahref="034.html"class="fetchSize">ThisTrickshot</a><br/>
  3. <ahref="assets/img/ball.png"class="fetchSize">Ball.png</a><br/>
  4. //Loopall.fetchSizelinks
  5. $('a.fetchSize').each(function(){
  6. //IssueanAJAXHEADrequestforeachone
  7. varlink=this;
  8. $.ajax({
  9. type:'HEAD',
  10. url:link.href,
  11. complete:function(xhr){
  12. //Appendthefilesizetoeach
  13. $(link).append('('+humanize(xhr.getResponseHeader('Content-Length'))+')');
  14. }
  15. });
  16. });
  17. functionhumanize(size){
  18. varunits=['bytes','KB','MB','GB','TB','PB'];
  19. varord=Math.floor(Math.log(size)/Math.log(1024));
  20. ord=Math.min(Math.max(0,ord),units.length-1);
  21. vars=Math.round((size/Math.pow(1024,ord))*100)/100;
  22. returns+''+units[ord];
  23. }

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

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

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

  1. //Thisisequivalenttopassingacallbackasthe
  2. //secondargument(executedonsuccess):
  3. $.get('assets/misc/1.json').done(function(r){
  4. log(r.message);
  5. });
  6. //Requestingafilethatdoesnotexist.Thiswilltrigger
  7. //thefailureresponse.Tohandleit,youwouldnormallyhaveto
  8. //usethefull$.ajaxmethodandpassitasafailurecallback,
  9. //butwithdeferredsyoucancansimplyusethefailmethod:
  10. $.get('assets/misc/non-existing.json').fail(function(r){
  11. log('Oops!Thesecondajaxrequestwas"'+r.statusText+'"(error'+r.status+')!');
  12. });

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

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

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

37.通过jQuery获得ip

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

  1. $.get('http://jsonip.com/',function(r){log(r.ip);});
  2. //Forolderbrowsers,whichdon'tsupportCORS
  3. //$.getJSON('http://jsonip.com/?callback=?',function(r){log(r.ip);});

38.使用最简单的ajax请求

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

  1. <pclass="content"></p><pclass="content"></p>
  2. varcontentDivs=$('.content');
  3. //Fetchthecontentsofatextfile:
  4. contentDivs.eq(0).load('1.txt');
  5. //FetchthecontentsofaHTMLfile,anddisplayaspecificelement:
  6. contentDivs.eq(1).load('1.html#header');

39.序列化对象

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

  1. <formaction="">
  2. Firstname:<inputtype="text"name="FirstName"value="Bill"/><br/>
  3. Lastname:<inputtype="text"name="LastName"value="Gates"/><br/>
  4. </form>
  5. //TurnallformfieldsintoaURLfriendlykey/valuestring.
  6. //ThiscanbepassedasargumentofAJAXrequests,orURLs.
  7. $(document).ready(function(){
  8. console.log($("form").serialize());//FirstName=Bill&LastName=Gates
  9. });
  10. //Youcanalsoencodeyourownobjectswiththe$.parammethod:
  11. log($.param({'pet':'cat','name':'snowbell'}));

©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经

(0)
打赏 微信扫码打赏 微信扫码打赏 支付宝扫码打赏 支付宝扫码打赏
清一色的头像清一色管理团队
上一篇 2023年5月4日 20:22
下一篇 2023年5月4日 20:22

相关推荐

发表评论

登录后才能评论

联系我们

在线咨询:1643011589-QQbutton

手机:13798586780

QQ/微信:1074760229

QQ群:551893940

工作时间:工作日9:00-18:00,节假日休息

关注微信