zoukankan      html  css  js  c++  java
  • JS代码优化及技巧

    案例一  对象参数独立化

    情景:为多个日期文本框添加日期选择器

    源代码:

    $('#PropertySalesAdviceExchnagedDate1').datepicker({
        showOn: 'button',
        buttonImage: '/img/calendar.gif',
        buttonImageOnly: true,
        changeYear : true,
        changeMonth : true,
        dateFormat:"dd/mm/yy"
    });
    
    $('#PropertySalesAdviceSettledDate1').datepicker({
        showOn: 'button',
        buttonImage: '/img/calendar.gif',
        buttonImageOnly: true,
        changeYear : true,
        changeMonth : true,
        dateFormat:"dd/mm/yy"
    });
    
    $('#PropertySalesAdviceFinanceDate1').datepicker({
        showOn: 'button',
        buttonImage: '/img/calendar.gif',
        buttonImageOnly: true,
        changeYear : true,
        changeMonth : true,
        dateFormat:"dd/mm/yy"
    });

    用到了jQueryUI里日期选择器的插件。datepicker接收一个对象作为参数。而且我们发现参数都一样,这样完全可以剥离出来。写在 datepicker_options 这个对象里。

    datepicker_options = {
      showOn: 'button',
      buttonImage: '/img/calendar.gif',
      buttonImageOnly: true,
      changeYear : true,
      changeMonth : true,
      // 去掉这行,默认的格式就是dd/mm/yy
      // dateFormat:"dd/mm/yy"          
    };
    //原来必须点小图标才会弹出日历,用户体验不要,改为获得焦点就弹出
    $('#PropertySalesAdviceExchnagedDate1,
      #PropertySalesAdviceSettledDate1,
      #PropertySalesAdviceFinanceDate1').datepicker(datepicker_options).bind('focus',function(){
      $(this).datepicker("show"); 
    });

    案例二  构建字符串的最优方法

    当你需要遍历数组或对象的时候,不要总想着“for”语句,要有创造性,总能找到更好的办法,例如,像下面这样。

    var arr = ['item 1', 'item 2', 'item 3']; 
    var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

     arr.join('</li><li>') 会生成字符串 "item 1</li><li>item 2</li><li>item 3"

    案例三  将方法放入到匿名函数中

    (function(){
    var a = function (){
    alert("hello")    
    }
    // 将a方法挂载到window对象上
    window.$ = a;
    })()
    
    $();

     四

    避免使用连续的声明,如在下面的例子里,a是局部变量,而b则是全局的(这和一般人的认知可能会不相同)。

    function foo() {
          var a = b = 0;  //等同于var a = (b = 0);使得b“变成”了全局变量
          // ...
    }

    所以可以这么做

    function foo() {
          var a, b;
          // ...
          a = b = 0; // both local
    }

    5. ~~可视为parseInt的缩写,而且速度更快

    6. 类型转换 

    // 结果 ['1', '2', '3']
    [1,2,3].map(String) 
    
    // 结果 [1, 2, 3]
    ['1','2','3'].map(Number) 
  • 相关阅读:
    Nginx 之负载均衡与反向代理
    PHP 之快递100接口封装
    Mongodb非关系型数据库
    Sphinx全文索引引擎
    PHP 之文件上传类封装
    PHP 之验证码类封装
    小程序 之左滑删除
    PHP 之实现按日期进行分组、分页
    System.IO 二
    IIS配置MIME类型
  • 原文地址:https://www.cnblogs.com/mafeifan/p/3288854.html
Copyright © 2011-2022 走看看