15个相当不错的jquery技巧

今天在tutorialzine发现一篇关于jquery使用技巧的,相当不错,翻译分享给各位。

1.使用最新的jquery版本

明河觉得这个建议有待商榷,虽然越新的jquery版本性能上更加优秀,但是有些方法的变迁还是会导致一些bug,比如从1.4.2到1.5时很多朋友就抱怨ajax上出现问题了。明河的建议是旧的页面的jquery升级需谨慎,新项目可以大胆的使用jquery新版本。
还有个建议是使用google的cdn上的jquery文件,加载速度更快。猛击Google Libraries API 进入查看。

  1. <!-- Include a specific version of jQuery -->
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  3. <!-- Include the latest version in the 1.6 branch -->
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
2.保持选择器的简单

这个建议明河非常赞同,有很多朋友不喜欢给元素增加样式或id,希望保持html的简洁,使用jquery强大的选择器去检索元素,这不是好的习惯。首先越复杂的选择器,遍历的效率越低,这是显而易见的,最高效率无疑是使用原生的getElementById();其次,复杂的选择器将标签名称和层级结构固化在里面,假如你的html结构发生了改变,或标签发生了改变,都直接造成检索失败。

  1. $('li[data-selected="true"] a')    // Fancy, but slow
  2. $('li.selected a')    // Better
  3. $('#elem')    // Best

访问DOM,是javascript最耗资源和性能的部分,所以尽量避免复杂或重复的遍历DOM
避免重复遍历DOM的方法就是将$()检索的元素存储到变量,比如下面的代码:

  1. var buttons = $('#navigation a.button');
  2. // 使用$前缀来标示jquery对象,是非常好的习惯,推荐使用。
  3. var $buttons = $('#navigation a.button');

jquery选择器支持大部分的css3伪类方法,像:visible:hidden:animated,虽然很便利,但请慎用,因为当你使用伪类选择器的时候,jQuery不得不使用querySelectorAll(),性能的损耗更大。

3.jQuery对象作为数组处理

jQuery对象定义了length属性,当使用数组的形式操作时候返回其实是DOM元素而不是子jQuery对象,比如下面代码。

  1. // Selecting all the navigation buttons:
  2. var buttons = $('#navigation a.button');
  3.  
  4. // 遍历buttons对象
  5. for(var i=0;i<buttons.length;i++){
  6.     console.log(buttons[i]);    // 是DOM元素,而不是jQuery对象!
  7. }
  8.  
  9. // We can even slice it:
  10. var firstFour = buttons.slice(0,4);

根据实验,使用for或while循环,执行效率比$.each()来的高。详细测试可以看several times faster
使用length属性来检查元素存在性:

  1. if(buttons){    // This is always true
  2.     // Do something
  3. }
  4.  
  5. if(buttons.length){ // True only if buttons contains elements
  6.     // Do something
  7. }
4.selector属性

jQuery对象都带有一个selector属性,用于获取选择器名称,比如:

  1. $('#container li:first-child').selector    // #container li:first-child
  2. $('#container li').filter(':first-child').selector    // #container li.filter(:first-child)

留意第二行代码,selector返回的是获取的元素完整的选择器。
这个属性常用于编写jquery插件的时候。

5.创建一个空的jQuery对象

这种情况应用场景不多,当你需要先创建个空的jQuery对象,然后使用add()方法向此对象注入jQuery对象时会用到。

  1. var container = $([]);
  2. container.add(another_element);)
6.选择随机元素

应用场景不多,举个例子,现在你需要随机给li增加一个red的class。

  1. (function($){
  2.     var random = 0;
  3.  
  4.     $.expr[':'].random = function(aimr) {
  5.         if (i == 0) {
  6.             random = Math.floor(Math.random() * r.length);
  7.         }
  8.         return i == random;
  9.     };
  10.  
  11. })(jQuery);
  12.  
  13. $('li:random').addClass('glow');

需要扩展jquery的选择器,这段代码很好的演示了jQuery.expr的用法。

7.使用css钩子

jQuery.cssHooks是1.4.3新增的方法,用的不估计不多,当你定义新的CSS Hooks时实际上定义的是getter和setter方法,举个例子,border-radius这个圆角属性想要成功应用于firefox、webkit等浏览器,需要增加属性前缀,比如-moz-border-radius和-webkit-border-radius。你可以通过定义CSS Hooks将其封装成统一的接口borderRadius,而不是一一设置css属性。

  1. $.cssHooks['borderRadius'] = {
  2. &nbsp; &nbsp; &nbsp; &nbspgetfunction(elemcomputedextra){
  3. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp// Depending on the browser, read the value of
  4.             // -moz-border-radius, -webkit-border-radius or border-radius
  5. &nbsp; &nbsp; &nbsp; &nbsp},
  6. &nbsp; &nbsp; &nbsp; &nbspsetfunction(elemvalue){
  7. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp// Set the appropriate CSS3 property
  8. &nbsp; &nbsp; &nbsp; &nbsp}
  9. };
  10.  
  11. // Use it without worrying which property the browser actually understands:
  12. $('#rect').css('borderRadius',5);
8.使用自定义的Easing(缓动动画效果)函数

easing plugin是用的非常多的函数,可以实现不少华丽的效果。当内置的缓动效果无法满足你的需求时,还可以自定义缓动函数。

  1. $.easing.easeInOutQuad = function (xtbcd) {
  2.     if ((t/=d/2) < 1) return c/2*t*t + b;
  3.     return -c/2 * ((--t)*(t-2) - 1) + b;
  4. };
  5.  
  6. // To use it:
  7. $('#elem').animate({width:200},'slow','easeInOutQuad');
9.$.proxy()的使用

关于$.proxy(),明河曾经详细介绍过,传送门在此《jquery1.4教程三:新增方法教程(3)》
jquery有个让人头疼的地方,回调函数过多,上下文this总是在变化着,有时候我们需要控制this的指向,这时候就需要$.proxy()方法。

  1. <div id="panel" style="display:none">
  2.     <button>Close</button>
  3. </div>
  1. $('#panel').fadeIn(function(){
  2.     // this points to #panel
  3.     $('#panel button').click(function(){
  4.         // this points to the button
  5.         $(this).fadeOut();
  6.     });
  7. });

嵌套的二个回调函数this指向是不同的!现在我们希望this的指向是#panel的元素。代码如下:

  1. $('#panel').fadeIn(function(){
  2.     // Using $.proxy to bind this:
  3.  
  4.     $('#panel button').click($.proxy(function(){
  5.         // this points to #panel
  6.         $(this).fadeOut();
  7.     },this));
  8. });
10.快速获取节点数

这是个常用的技巧,代码如下:

  1. console.log( $('*').length );
11.构建个jquery插件
  1. (function($){
  2.     $.fn.yourPluginName = function(){
  3.         // Your code goes here
  4.         return this;
  5.     };
  6. })(jQuery);

关于jquery插件的构建,明河曾发过系列教程,传送门:制作jquery文字提示插件—jquery插件实战教程(1)
这里就不再详述。

12.设置ajax全局事件

关于ajax全局事件,明河曾发过完整的介绍文章,传送门:《jquery的ajax全局事件详解—明河谈jquery》。

13.延迟动画
  1. // This is wrong:
  2. $('#elem').animate({width:200},function(){
  3.     setTimeout(function(){
  4.         $('#elem').animate({marginTop:100});
  5.     },2000);
  6. });
  7.  
  8. // Do it like this:
  9. $('#elem').animate({width:200}).delay(2000).animate({marginTop:100});

当存在多个animate动画时,如何处理动画的执行顺序是个烦心事,原文作者是建议使用delay()函数,如上面的代码,但明河的建议是使用queue()方法,因为delay你要考虑延迟多少时间,而queue没有这个问题,进入队列的函数会一个个顺序执行。可以看明河以前的文章queue和dequeue—明河谈jquery

15.jquery的本地存储

本地存储在现在web应用中使用越来越频繁,jquery有个专门用于本地存储的插件叫$.jStorage jQuery plugin

  1. // Check if "key" exists in the storage
  2. var value = $.jStorage.get("key");
  3. if(!value){
  4.     // if not - load the data from the server
  5.      value = load_data_from_server();
  6.      // and save it
  7.     $.jStorage.set("key",value);
  8. }
  9.  
  10. // Use value

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值