提高jQuery效率

来源:互联网 发布:windows http服务器 编辑:程序博客网 时间:2024/06/07 15:23



  1.      1.缓存变量
            DOM遍历是昂贵的,所以尽量将会重用的元素缓存。
    1. // 糟糕

    2. h = $('#element').height();
    3. $('#element').css('height',h-20);

    4. // 建议

    5. $element = $('#element');
    6. h = $element.height();
    7. $element.css('height',h-20);
         2.使用匈牙利命名法
           在变量前加$前缀,便于识别出jQuery对象。
    1. // 糟糕

    2. var first = $('#first');
    3. var second = $('#second');
    4. var value = $first.val();

    5. // 建议 - 在jQuery对象前加$前缀

    6. var $first = $('#first');
    7. var $second = $('#second'),
    8. var value = $first.val();

    9. 3.请使用’On’
    10. 在新版jQuery中,更短的 on(“click”) 用来取代类似 click() 这样的函数。在之前的版本中 on() 就是 bind()。自从jQuery 1.7版本后,on() 附加事件处理程序的首选方法。然而,出于一致性考虑,你可以简单的全部使用 on()方法。
      1. // 糟糕

      2. $first.click(function(){
      3.     $first.css('border','1px solid red');
      4.     $first.css('color','blue');
      5. });

      6. $first.hover(function(){
      7.     $first.css('border','1px solid red');
      8. })

      9. // 建议
      10. $first.on('click',function(){
      11.     $first.css('border','1px solid red');
      12.     $first.css('color','blue');
      13. })

      14. $first.on('hover',function(){
      15.     $first.css('border','1px solid red');
      16. })
      17. 4.维持代码的可读性
        伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。
        1. // 糟糕

        2. $second.html(value);
        3. $second.on('click',function(){
        4.     alert('hello everybody');
        5. }).fadeIn('slow').animate({height:'120px'},500);

        6. // 建议

        7. $second.html(value);
        8. $second
        9.     .on('click',function(){ alert('hello everybody');})
        10.     .fadeIn('slow')
        11.     .animate({height:'120px'},500);
        5.熟记技巧
        你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。
        1. // 糟糕

        2. $('#id').data(key,value);

        3. // 建议 (高效)

        4. $.data('#id',key,value);
        6.使用子查询缓存的父元素
        正如前面所提到的,DOM遍历是一项昂贵的操作。典型做法是缓存父元素并在选择子元素时重用这些缓存元素。
        1. // 糟糕

        2. var 
        3.     $container = $('#container'),
        4.     $containerLi = $('#container li'),
        5.     $containerLiSpan = $('#container li span');

        6. // 建议 (高效)

        7. var 
        8.     $container = $('#container '),
        9.     $containerLi = $container.find('li'),
        10.     $containerLiSpan= $containerLi.find('span');

0 0
原创粉丝点击