JS 筆記整理

在前端工做期間遇到過很多的問題,不少時候這些問題也是反覆出現的,是時候將問題都記錄下來,用於回顧及避免反覆浪費時間在同一問題上。

一、對象轉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

二、日期格式化

/**
 * 對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;
}

三、模板字符串實現

/**
 * 模板字符串實現,將指定內容賦值給字符串中的參數字段
 * 
 * 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;
};

四、文件下載

關於下載能夠先閱讀 https://www.cnblogs.com/husts...

a標籤 & window.open() javascript

// 瀏覽器支持可以打開的格式,他都會默認直接在線打開(好比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 html

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及以上支持java

$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 兼容性處理 jquery

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生成EXCELgit

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

五、文件上傳

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

六、防止網頁被嵌入框架

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;
}

七、快速排序

http://www.ruanyifeng.com/blo...

八、cookie設置及獲取

//寫cookies(設置做用域)
function setCookie(name,value,days){
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + days*24*60*60*1000);
    let hostname = location.hostname.substring(location.hostname.indexOf(".")+1)  //設置爲一級域名
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";domain="+hostname+";path=/";
}
  
//讀取cookies
function getCookie(name)
{
     var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
     if(arr=document.cookie.match(reg))
         return (arr[2]);
     else
        return null;
}
 
//刪除cookies
function delCookie(name){
    setCookie(name, '', -1)
}

九、獲取URL參數

// 獲取參數值
function getQueryString(name) { 
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
    var r = window.location.search.substr(1).match(reg); 
    if (r != null) return unescape(r[2]); 
    return null; 
}

// 獲取url中的參數並以對象的形式展現出來
function getUrlData(){
    let url=window.location.search;//url中?以後的部分
    console.log('url....'+url)
    url=url.substring(1);//去掉?剩下的都爲a=b&c=d&e=f...模式
    console.log('去掉?....'+url)
    let dataObj={};
    if(url.indexOf('&')>-1){
        url=url.split('&');//url中去掉&所有變成「a=b」 「c=d」 「e=f」的模式
        console.log('去掉&的url...'+url)
        for(let i=0;i<url.length;i++){
            let arr=url[i].split("=");
            console.log("以=分割的代碼...."+arr)
            dataObj[arr[0]]=arr[1];
            console.log("dataObj..."+dataObj);
        }

    }else{
        url=url.split("=");
        dataObj[url[0]]=url[1];
    }
    return dataObj;
}

十、判斷是否爲對象

// isObjectEqual
export function isObjectValueEqual (a, b) {
  let o1 = a instanceof Object;
  let o2 = b instanceof Object;

  if (!o1 || !o2) {
    return a === b;
  }

  let aProps = Object.getOwnPropertyNames(a);
  let bProps = Object.getOwnPropertyNames(b);

  for (let i = 0; i < aProps.length; i++) {
    let t1 = aProps[i] instanceof Object;
    let t2 = bProps[i] instanceof Object;

    if (t1 && t2) {
      return isObjectValueEqual(aProps[i], bProps[i]);
    } else if (aProps[i].indexOf('_') !== 0 && a[aProps[i]] !== b[aProps[i]]) {
      return false;
    }
  }
  return true;
}

十一、判斷IE瀏覽器版本

export function IEVersion () {
  let userAgent = navigator.userAgent; // 取得瀏覽器的userAgent字符串
  let isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; // 判斷是否IE<11瀏覽器
  let isEdge = userAgent.indexOf('Edge') > -1 && !isIE; // 判斷是否IE的Edge瀏覽器
  let isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;

  if (isIE) {
    let reIE = new RegExp('MSIE (\\d+\\.\\d+);');

    reIE.test(userAgent);

    let fIEVersion = parseFloat(RegExp['$1']);

    if (fIEVersion === 7) {
      return 7;
    } else if (fIEVersion === 8) {
      return 8;
    } else if (fIEVersion === 9) {
      return 9;
    } else if (fIEVersion === 10) {
      return 10;
    } else {
      return 6; // IE版本<=7
    }
  } else if (isEdge) {
    return 'edge'; // edge
  } else if (isIE11) {
    return 11; // IE11
  } else {
    return -1; // 不是ie瀏覽器
  }
}

十二、事件延時

export function debounce (func, delay) {
  let timer;

  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
相關文章
相關標籤/搜索