zoukankan      html  css  js  c++  java
  • 高效jQuery

    1.缓存变量

    DOM遍历是昂贵的,所以尽量将会重用的元素缓存。

    // 糟糕
    
    h = $('#element').height();
    $('#element').css('height',h-20);
    
    // 建议
    
    $element = $('#element');
    h = $element.height();
    $element.css('height',h-20);

    2.使用’On’

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

    // 糟糕
    
    $first.click(function(){
        $first.css('border','1px solid red');
        $first.css('color','blue');
    });
    
    $first.hover(function(){
        $first.css('border','1px solid red');
    })
    
    // 建议
    $first.on('click',function(){
        $first.css('border','1px solid red');
        $first.css('color','blue');
    })
    
    $first.on('hover',function(){
        $first.css('border','1px solid red');
    })

    3.
    链式操作

    jQuery实现方法的链式操作是非常容易的。下面利用这一点。

    // 糟糕
    
    $second.html(value);
    $second.on('click',function(){
        alert('hello everybody');
    });
    $second.fadeIn('slow');
    $second.animate({height:'120px'},500);
    
    // 建议
    
    $second.html(value);
    $second.on('click',function(){
        alert('hello everybody');
    }).fadeIn('slow').animate({height:'120px'},500);

    4.
    熟记技巧

    你可能对使用jQuery中的方法缺少经验,一定要查看的文档,可能会有一个更好或更快的方法来使用它。

    // 糟糕
    
    $('#id').data(key,value);
    
    // 建议 (高效)
    
    $.data('#id',key,value);

    5.
    避免通用选择符

    将通用选择符放到后代选择符中,性能非常糟糕。

    // 糟糕
    
    $('.container > *'); 
    
    // 建议
    
    $('.container').children();

    6.
    避免隐式通用选择符

    通用选择符有时是隐式的,不容易发现。

    // 糟糕
    
    $('.someclass :radio'); 
    
    // 建议
    
    $('.someclass input:radio');
  • 相关阅读:
    asp.net webform 增加 loading
    DataTable 数据筛选
    c# float 类型传入 sql server float 参数导致结果错误
    Delphi Modal窗体(ModalResult、ShowModal)的介绍、使用方法和注意事项
    通用流水线处理器技术参数
    处理器系列技术参数
    云端一体全栈解决方案
    Camera系列规格参数
    分立器件成品参数
    新能源与智能制造
  • 原文地址:https://www.cnblogs.com/dacuotecuo/p/3470652.html
Copyright © 2011-2022 走看看