zoukankan      html  css  js  c++  java
  • 15个相当不错的jQuery技巧

    1.使用最新的jquery版本

    明河觉得这个建议有待商榷,虽然越新的jquery版本性能上更加优秀,但是有些方法的变迁还是会导致一些bug,比如从1.4.2到1.5时很多朋友就抱怨ajax上出现问题了。明河的建议是旧的页面的jquery升级需谨慎,新项目可以大胆的使用jquery新版本。
    还有个建议是使用google的cdn上的jquery文件,加载速度更快。猛击Google Libraries API 进入查看。
    <!-- Include a specific version of jQuery -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <!-- Include the latest version in the 1.6 branch -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>


    2.保持选择器的简单

    这个建议明河非常赞同,有很多朋友不喜欢给元素增加样式或id,希望保持html的简洁,使用jquery强大的选择器去检索元素,这不是好的习惯。首先越复杂的选择器,遍历的效率越低,这是显而易见的,最高效率无疑是使用原生的getElementById();其次,复杂的选择器将标签名称和层级结构固化在里面,假如你的html结构发生了改变,或标签发生了改变,都直接造成检索失败。
    $('li[data-selected="true"] a') // Fancy, but slow
    $('li.selected a') // Better
    $('#elem') // Best
    访问DOM,是javascript最耗资源和性能的部分,所以尽量避免复杂或重复的遍历DOM。
    避免重复遍历DOM的方法就是将$()检索的元素存储到变量,比如下面的代码:
    var buttons = $('#navigation a.button');
    // 使用$前缀来标示jquery对象,是非常好的习惯,推荐使用。
    var $buttons = $('#navigation a.button');
    jquery选择器支持大部分的css3伪类方法,像:visible, :hidden, :animated,虽然很便利,但请慎用,因为当你使用伪类选择器的时候,jQuery不得不使用querySelectorAll(),性能的损耗更大。


    3.jQuery对象作为数组处理

    jQuery对象定义了length属性,当使用数组的形式操作时候返回其实是DOM元素而不是子jQuery对象,比如下面代码。
    // Selecting all the navigation buttons:
    var buttons = $('#navigation a.button');

    // 遍历buttons对象
    for(var i=0;i<buttons.length;i++){
    console.log(buttons[i]); // 是DOM元素,而不是jQuery对象!
    }

    // We can even slice it:
    var firstFour = buttons.slice(0,4);
    根据实验,使用for或while循环,执行效率比$.each()来的高。详细测试可以看several times faster。
    使用length属性来检查元素存在性:
    if(buttons){ // This is always true
    // Do something
    }

    if(buttons.length){ // True only if buttons contains elements
    // Do something
    }


    4.selector属性

    jQuery对象都带有一个selector属性,用于获取选择器名称,比如:
    $('#container li:first-child').selector // #container li:first-child
    $('#container li').filter(':first-child').selector // #container li.filter(:first-child)
    留意第二行代码,selector返回的是获取的元素完整的选择器。
    这个属性常用于编写jquery插件的时候。


    5.创建一个空的jQuery对象

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


    6.选择随机元素

    应用场景不多,举个例子,现在你需要随机给li增加一个red的class。
    (function($){
    var random = 0;

    $.expr[':'].random = function(a, i, m, r) {
    if (i == 0) {
    random = Math.floor(Math.random() * r.length);
    }
    return i == random;
    };

    })(jQuery);

    $('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属性。
    $.cssHooks['borderRadius'] = {
    &nbsp; &nbsp; &nbsp; &nbsp; get: function(elem, computed, extra){
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Depending on the browser, read the value of
    // -moz-border-radius, -webkit-border-radius or border-radius
    &nbsp; &nbsp; &nbsp; &nbsp; },
    &nbsp; &nbsp; &nbsp; &nbsp; set: function(elem, value){
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Set the appropriate CSS3 property
    &nbsp; &nbsp; &nbsp; &nbsp; }
    };

    // Use it without worrying which property the browser actually understands:
    $('#rect').css('borderRadius',5);


    8.使用自定义的Easing(缓动动画效果)函数

    easing plugin是用的非常多的函数,可以实现不少华丽的效果。当内置的缓动效果无法满足你的需求时,还可以自定义缓动函数。
    $.easing.easeInOutQuad = function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * ((--t)*(t-2) - 1) + b;
    };

    // To use it:
    $('#elem').animate({200},'slow','easeInOutQuad');


    9.$.proxy()的使用

    关于$.proxy(),明河曾经详细介绍过,传送门在此《jquery1.4教程三:新增方法教程(3)》。
    jquery有个让人头疼的地方,回调函数过多,上下文this总是在变化着,有时候我们需要控制this的指向,这时候就需要$.proxy()方法。
    <div id="panel" style="display:none">
    <button>Close</button>
    </div>
    $('#panel').fadeIn(function(){
    // this points to #panel
    $('#panel button').click(function(){
    // this points to the button
    $(this).fadeOut();
    });
    });
    嵌套的二个回调函数this指向是不同的!现在我们希望this的指向是#panel的元素。代码如下:
    $('#panel').fadeIn(function(){
    // Using $.proxy to bind this:

    $('#panel button').click($.proxy(function(){
    // this points to #panel
    $(this).fadeOut();
    },this));
    });


    10.快速获取节点数

    这是个常用的技巧,代码如下:
    console.log( $('*').length );


    11.构建个jquery插件

    (function($){
    $.fn.yourPluginName = function(){
    // Your code goes here
    return this;
    };
    })(jQuery);
    关于jquery插件的构建,明河曾发过系列教程,传送门:制作jquery文字提示插件—jquery插件实战教程(1)。
    这里就不再详述。


    12.设置ajax全局事件

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


    13.延迟动画

    // This is wrong:
    $('#elem').animate({200},function(){
    setTimeout(function(){
    $('#elem').animate({marginTop:100});
    },2000);
    });

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


    15.jquery的本地存储

    本地存储在现在web应用中使用越来越频繁,jquery有个专门用于本地存储的插件叫$.jStorage jQuery plugin。
    // Check if "key" exists in the storage
    var value = $.jStorage.get("key");
    if(!value){
    // if not - load the data from the server
    value = load_data_from_server();
    // and save it
    $.jStorage.set("key",value);
    }

    // Use value

  • 相关阅读:
    聚合根、实体、值对象
    哀悼的CSS 把网站变成灰色
    Ubuntu13.04更换aptget源
    JS判断用户终端,跳转到不同的页面.
    分享一个使用的FireFox 截图插件小巧方便
    Linux 下面FireFox 看CCTV直播
    Ubuntu 11.10后 Guest账户禁用!
    修改Ubuntu的启动画面plymouth
    ubuntu开机自启动小键盘
    Linux 用cat做图片种子||Windows 用copy做图片种子
  • 原文地址:https://www.cnblogs.com/Qzhou/p/3022853.html
Copyright © 2011-2022 走看看