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');
  • 相关阅读:
    UVA 10600 ACM Contest and Blackout(次小生成树)
    UVA 10369
    UVA Live 6437 Power Plant 最小生成树
    UVA 1151 Buy or Build MST(最小生成树)
    UVA 1395 Slim Span 最小生成树
    POJ 1679 The Unique MST 次小生成树
    POJ 1789 Truck History 最小生成树
    POJ 1258 Agri-Net 最小生成树
    ubuntu 用法
    ubuntu 搭建ftp服务器,可以通过浏览器访问,filezilla上传文件等功能
  • 原文地址:https://www.cnblogs.com/dacuotecuo/p/3470652.html
Copyright © 2011-2022 走看看