JS 笔记整理

接触前端已经快两年,在这期间遇到过问题,很多时候这些问题也是反复出现的,我觉得我应该从现在开始将问题都记录下来,用于回顾及避免反复浪费时间在同一问题上。

1、对象转URL参数

var parseParam=function(param, key){ 
  var paramStr=""; 
  if(param instanceof String || param instanceof Number || param instanceof Boolean){ 
    paramStr += "&" + key + "=" + encodeURIComponent(param);
  }else{ 
    $.each(param,function(i){
      var k = key==null ? i : key + (param instanceof Array ? "["+i+"]" : "."+i); 
      paramStr += '&' + parseParam(this, k); 
    }); 
  } 
  return paramStr.substr(1);
};

var a = {a: 'a', b: 'b'};
console.log(parseParam(a)); // a=a&b=b
console.log(parseParam(a, 'person')); // person.a=a&person.b=b

2、日期格式化

/**
 * 对Date的扩展,将 Date 转化为指定格式的String 
 * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
 * 
 * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
 * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
 * 
 * @param {*} fmt 
 */
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

3、模板字符串实现

/**
 * 模板字符串实现,将指定内容赋值给字符串中的参数字段
 * 
 * var url = '../img/bookList/img_{0}.png';
 * url.format('a1');
 * 
 * @param {*} args 
 */
String.prototype.format = function (args) {
  var result = this;
  if (arguments.length > 0) {
      if (arguments.length == 1 && typeof (args) == "object") {
          for (var key in args) {
              if (args[key] != undefined) {
                  var reg = new RegExp("({" + key + "})", "g");
                  result = result.replace(reg, args[key]);
              }
          }
      }
      else {
          for (var i = 0; i < arguments.length; i++) {
              if (arguments[i] != undefined) {
                  var reg = new RegExp("({[" + i + "]})", "g");
                  result = result.replace(reg, arguments[i]);
              }
          }
      }
  }
  return result;
};

4、文件下载

关于下载可以先阅读 https://www.cnblogs.com/husts...

a标签 & window.open()

// 浏览器支持能够打开的格式,他都会默认直接在线打开(比如word或图片),不支持的格式,他就会弹出下载提示。最好是做成.rar格式的文件
 $btn.click(function(){window.open("xxxxx/file.rar");});

// 使用download属性
<a href="large.jpg" download>下载</a>
var isSupportDownload = 'download' in document.createElement('a'); // 监测当前浏览器是否支持download属性

Iframe

try {
  requestTaskByForm();
  startTask(translateResponse, 0, iInterval, iTimeout);
} catch (exp) {
    console.err(exp);
}    

// config 下载JSON报文配置项;timeout 超时(毫秒),默认60000;interval 轮询间隔(毫秒),默认100;callback 回调函数;err 异常回调;scope 作用域;url 下载servlet,默认cifjsondownload;

/*
  * isArray
  * @param v
  * @returns {Boolean}
  */
function isArray(v){
  return !!v && Object.prototype.toString.call(v) === '[object Array]';
};

/**
 * isObject
 * @param v
 * @returns {Boolean}
 */
function isObject(v){
  return !!v && Object.prototype.toString.call(v) === '[object Object]';
};

/**
 * json object copy
 * @param o
 * @param c
 */
function apply(o,c){
  if (isObject(c)) {
    for (var p in c) {
      if (o.hasOwnProperty(p.toString().toUpperCase()))
        o[p.toString().toUpperCase()] = c[p];
      if (o.hasOwnProperty(p))
        o[p] = c[p];
    }
  }            
};

/**
 * parseJson
 * @param message
 */
function parseJson(res){
  return eval('(' + res + ')');
};
    /**
 * init json body
 */
function initJsonElements(){
  apply(oCif, oConfig);
}

/**
 * init html elements
 */
function initHtmlElements(){
  requestDiv = document.getElementById(reqDivId);
  if(!requestDiv){
    requestDiv = document.createElement("div");
    requestDiv.id = reqDivId;
    requestDiv.innerHTML = '<iframe id='+reqIframeId+' name='+reqIframeId+'></iframe>';
    requestDiv.style.display = 'none';
    document.body.appendChild(requestDiv);
  }
  requestForm = document.getElementById(reqFromId);
  if(requestForm){
    document.body.removeChild(requestForm);
  }
  requestForm = document.createElement("form");
  requestForm.id = reqFromId;
  requestForm.method = 'POST';
  requestForm.action = sUrl;
  requestForm.target = reqIframeId ;
  requestForm.style.display = 'none';
  document.body.appendChild(requestForm);
};

/**
 * init form childs
 * @param data
 * @param parent
 */
function initFormElements(data, parent){
  for(var c in data){
    if (data.hasOwnProperty(c)){
      if(isArray(data[c])){
        initFormElements(data[c][0], c);
      }else if(isObject(data[c])){
        initFormElements(data[c], c);
      }else{
        if(parent){
          var seq = document.createElement("input");
          seq.type = 'hidden';
          seq.name = parent +'.'+ c ;
          seq.value = data[c];
          requestForm.appendChild(seq);
        }else{
          var seq = document.createElement("input");
          seq.type = 'hidden';
          seq.name = c ;
          seq.value = data[c];
          requestForm.appendChild(seq);                            
        }                        
      }                    
    }
  }            
}

/**
 * request task by form
 */
function requestTaskByForm(){
  initJsonElements();
  initHtmlElements();
  initFormElements(oCif);
  if(requestForm)requestForm.submit();
}        

/**
 * init iframe response innerHTML
 */
function initResponse(){
  requestIframe = document.getElementById(reqIframeId);
  var iframeWindow = document.getElementById(reqIframeId).contentWindow ;
  if(iframeWindow 
      && iframeWindow.document
      && iframeWindow.document.body
      && iframeWindow.document.body.innerHTML){
    iframeWindow.document.body.innerHTML='';
  }            
}

/**
 * stopTask
 * @param intervalId
 */
function stopTask(intervalId){
  clearInterval(intervalId);
  initResponse();
};

/**
 * startTask
 * @param func
 * @param start
 * @param interval
 * @param end
 */
function startTask(func, start, interval, end){
  if (!start) start = 0;
  if (arguments.length <= 2){
    setTimeout(func, start);
  }else{
    function repeat() {
      taskId = setInterval(func, interval);
      if (end) setTimeout(function() { 
        stopTask(taskId);
      }, end);
    };                
    setTimeout(repeat, start);
  }            
};

/**
 * translate response
 */
function translateResponse(){
  var iframeWindow = document.getElementById(reqIframeId).contentWindow ;
  if(iframeWindow 
      && iframeWindow.document
      && iframeWindow.document.body
      && iframeWindow.document.body.innerHTML){
    var res = iframeWindow.document.body.innerHTML;
    if(res !=''){
      var response = parseJson(res);
      if(response.RTNCOD == 'SUC0000'){
        initResponse();
        if(requestForm)requestForm.submit();
      }else{
        if(scope)
          fCallback.call(scope,res);
        else
          fCallback.call(this,res);
        stopTask(taskId);                        
      }
    }
  }
};

API下载

Blob 对象只有在IE10及以上支持

$http({
        url: 'http://xxxx/xxxx',
        method: 'post',
        data: {
            type: '类型',
            selectedCols: '选择的列'
        },
        dataType: 'json',
        responseType: 'arraybuffer'
    }).success(function (data, status, headers, config) {
        var fileName = name +'-' + new Date();
        var blob = new Blob([data], {type: "application/vnd.ms-excel"});
        if (window.navigator.msSaveOrOpenBlob){
            navigator.msSaveBlob(blob, fileName);//IE
        } else {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            window.URL.revokeObjectURL(link.href);
        }
    }).then(clear()).error(function (data, status, headers, config) {
       console.log('error');
    });

FileSaver.js 兼容性处理

https://github.com/eligrey/Fi...
Blob 对象只有在IE10及以上支持
var FileSaver = require('file-saver');
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

前端将table生成EXCEL

https://github.com/rainabba/j...
$("#yourHtmTable").table2excel({
    exclude: ".excludeThisClass",
    name: "表格名称",
    filename: "SomeFile" //do not include extension
});

5、文件上传

https://github.com/mailru/Fil...
https://github.com/transloadi...

6、防止网页被嵌入框架

try{

  top.location.hostname;

  if (top.location.hostname != window.location.hostname) {

    top.location.href =window.location.href;

  }

}

catch(e){

  top.location.href = window.location.href;

}

7、快速排序

http://www.ruanyifeng.com/blo...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值