js md5

来源:http://www.oschina.net/code/snippet_12_8927

/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/
  
var MD5 = function (string) {
  
    function RotateLeft(lValue, iShiftBits) {
        return (lValue<>>(32-iShiftBits));
    }
  
    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }
  
    function F(x,y,z) { return (x & y) | ((~x) & z); }
    function G(x,y,z) { return (x & z) | (y & (~z)); }
    function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }
  
    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
  
    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
  
    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
  
    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
  
    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<>>29;
        return lWordArray;
    };
  
    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };
  
    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
  
        for (var n = 0; n < string.length; n++) {
  
            var c = string.charCodeAt(n);
  
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
  
        }
  
        return utftext;
    };
  
    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;
  
    string = Utf8Encode(string);
  
    x = ConvertToWordArray(string);
  
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
  
    for (k=0;k
	

js 操作缓存变量 【原创辣鸡代码】

    /***
* Cache缓存管理
* @param type[string] eq-赋值/add-字符串增加/push-数组增加/extend-对象合并]
*/
function c( name, val ,type){
  //默认操作
  var type = type || "eq";
  //创造缓存空间
  if(typeof CACHE != "object"){CACHE={};}

  //指针定向到缓存
  var result = CACHE;

  //点语法,最终找到相关位置的父级
  if(name.match(/\./g)){
    var arr= name.split(".");
    arr.map(function(ele,ind){
      if(ind == arr.length -1 ){name = ele;return;}
      result = result[ele];
    })
    //找不到数据未定义
    if(!result){return false;}
  }

  //理解请求的操作
  var val_type = typeof val;
  var name_type = typeof name;
  //--理解为读取指定缓存 的逻辑
  if(val_type == "undefined"){return result[name];}
  //--理解为读取整个缓存 的逻辑
  if(name_type == "undefined"){return result;}

  //--下面是 对缓存进行操作的逻辑
  //-- -- 定义操作函数
  //-- -- --赋值
  function eq(){
    result[name] = val;
    return result[name];
  }
  //-- -- --字符串增加
  function add(){
    result[name] = (result[name])? result[name] + val : val;
    return result[name];
  }
  //-- -- --数组增加
  function push(){
    result[name].push( val );
    return result[name];
  }
  //-- -- --对象合并
  function extend(){
    if(typeof result[name] == "obj"){
      $.extend(result[name], val);
    }else{
      eq();
    }
    return result[name];
  }

  //-- -- 执行相关操作
  try{
    var run = `result= ${type}();`;
    eval(run);
  }catch(e){
    console.log(e);
    console.log(run);
    //操作失败返回错误
    result = false;
  }

  return result;
}

必填选项小插件

声明

需要jq

还需要我的其他小工具
* in_array

调用

      function mustFinish_init(){

    var mustFinish_list=[
      "username",
             "password",
    ]
    MF=new mustFinish();
        //简易用法
    //MF.init("label",mustFinish_list);
        //完整用法
        MF.labels=$(".clearfix > div > label");
    MF.list=mustFinish_list;
    MF.init();

  }
    mustFinish_init();

源码

    /*===========================================必填选项*/
function mustFinish(){
  var that=this;
  this.labels=$("label");//需要标*的地方
  this.list=[];//name数组

  this.init=function(labels,list){
    that.labels=(labels)?$(labels)||that.labels:that.labels;
    that.list=list||that.list;

    //必填选项标红
    that.labels.map(function(index,element){
      var namels=$(element).parent().find("[name]");
      var isInList=false;
      namels.map(function(ind,input){
        var namevalue=input.name;
        if(in_array(namevalue,that.list)){
          isInList=true;
        }
      })
      if(isInList){
        var span=createElement("span","","*");
        span.style.color="red";
        $(element).prepend(span);
      }
    })

  }
  this.check=function(){
    var isPass=true;
    that.list.map(function(ele,ind){
      // console.dir($("[name='"+ele+"']"))
      var obj=$("[name='"+ele+"']");
      var inputValue="";
      var Nodename=obj[0].nodeName;
      var inputType;
      if(Nodename=="SELECT"){inputType="select";}
      else{inputType=obj.attr("type");}


      switch (inputType) {
        case "text":
          obj=$(obj[0]);
          inputValue=obj.val();
          break;
        case "password":
          obj=$(obj[0]);
          inputValue=obj.val();
          break;
        case "radio":
          inputValue=obj.filter(":checked").val();
          break;
        case "checkbox":
          inputValue=obj.filter(":checked").map(function(c_ind,c_ele){return c_ele.value});
          break;
        case "select":
        // console.dir(obj);
          var selecter=obj[0];
          inputValue=selecter.selectedOptions[0].value;
          inputValue=(inputValue=="请选择")?"":inputValue;
          break;
        default:
          obj=$(obj[0]);
          inputValue=obj.val();
      }
      //console.log(inputValue);
      if(!inputValue||inputValue==""){
        isPass=false;
      }
    })
    return isPass;
  }
}

jtable bate

一些想法

1.需要保存获取数据接口和搜索接口
2.单元格区分 展示值和实际数值

如何调用

    ftable=new jtable();
    var f_post={
        "Json":{
            "alipay_name":$("#list_alipay_name :selected").text(),
            "alipay_name_id":$("#list_alipay_name :selected").attr("index_row"),
        }
    }
    ftable.post(u.file.list,f_post,function(ret){

        ftable.create({
            "ret":ret,
            "frame":{
                trans:[
                    ["t_id","ID","text"],
                ],
        }
    });


    })

css部分

/*sql_window*/
.sql_window_bg{
  position: absolute;
  width: 100%;
  height:100%;
  top:0;
  left: 0;
  z-index: 11;
}
.sql_window_con{
  position: absolute;
  width: 200px;
  height:300px;
  z-index: 12;
  background: #fff;
  border: 1px solid #ddd;
  border-width: 0 1px 4px 1px;
  padding:10px;
}

/*table补全*/
.table td{
  padding: 0 2px !important;
}
.table-bordered th,
 .table-bordered td {
   border: 1px solid #ddd !important;
 }
 .table-bordered th,
 .table-bordered td {
   border: 1px solid #ddd !important;
 }

.table-page-con{
  text-align: center !important;
  height:75px;
}
.table-page-con a{
  cursor:pointer;
}
.table-mubu{
  top:0;
  left:0;
  position: absolute;
  z-index: 99;
  width: 100%;
  height: 100%;
  background: rgba(255,255,255,.6);

}
.table td .input-group{
  max-width: 220px !important;
  min-width: 120px !important;
}
.table th {
  white-space: nowrap;
  padding:4px 3px !important;
}

插件定义部分




*/
//创建table
function jtable(){
    var that = this;
    this.url;//请求地址
    var post_data;//抛出数据
    this.trs=[];//全部tr
    this.th=[];//表头数据
    this.table=document.createElement("table");//表格
    this.css="table";
    this.table.className=this.css;
    this.sqlkey={};
    var callback;
    var ret;
    this.target=$(".maintable");//注入目标
    this.post=function(){
        this.loading();
        this.url=arguments[0];
        post_data=arguments[1];
        callback=(typeof(arguments[2])=="undefined")?callback:arguments[2];
        ajax(this.url,post_data,callback);
    }

    var frame={
        "trans":undefined,
        "hide":undefined,
        "fixed":undefined,
        "post_page_num":undefined,
        "search":undefined,
    }
    this.create=function(){
        this.loadend();
        this.target.empty();
        this.trs=[];//全部tr
        this.th=[];//表头数据
        this.table.innerHTML="";
        ret=arguments[0].ret;
        frame=(typeof(arguments[0].frame)=="undefined")?frame:arguments[0].frame;
        if(typeof(ret.data[0])=="undefined"){console.log("数据为空");return;}
        if(!(ret.data instanceof Array)){console.log("传入非数组");return;}
        //存在 页码字段
        if(!!ret.countnum&&!!ret.pagemax&&ret.pagemax>1){
            this.createpage(ret);
        }
        //不存在 sql_key 字段
        if(!post_data.Json.sql_key){
            that.sqlkey={};
        }
        for(var i =0 , len = ret.data.length; i= '"+keyvalue+"'",
                        sqlkey_field:type,
                    }
                    break;
                case "less":
                    that.sqlkey[sqlkey_field]={
                        "value":keyvalue,
                        "sqltext":sqlkey_field+" <= '"+keyvalue+"'",
                        sqlkey_field:type,
                    }
                    break;
            }
            var post_sql=[];

            // for(var sql_i in that.sqlkey){
            //  post_sql.push(that.sqlkey[sql_i].sqltext)
            // }
            post_data.Json.sql_key=that.sqlkey;
            console.table(that.sqlkey);
            console.log(post_data.Json.sql_key);

            // post_data.Json.sql_key
            that.post(that.url,post_data,callback)
            sql_w.close()
            }
        sql_w.init();


    }
}
function sql_window(){
    this.top=0;
    this.left=0;
    this.width=250;
    this.height="auto";
    this.father;
    this.result;
    this.ret;
    var that=this;
    this.init=function(){
        that.father.style.position="relative";
        var sql_bg=document.createElement("div");
        sql_bg.className="sql_window_bg";
        sql_bg.addEventListener("click",that.close);
        document.body.appendChild(sql_bg);

        var sql_w=document.createElement("div");
        sql_w.className="sql_window_con";
        sql_w.style.top=that.top +22+"px";
        var fatherLeft=that.father.offsetLeft;
        var winWidth=window.innerWidth;

        sql_w.style.left=that.left-((fatherLeft>(winWidth/2))?that.width:0)+"px";
        sql_w.style.width=this.width+"px";
        sql_w.style.height=this.height;
        this.father.appendChild(sql_w)
        //top
        var sql_w_top=document.createElement("div");
        sql_w_top.className=" sql_window_top";
        sql_w.appendChild(sql_w_top);
        //-close按钮
        var sql_close_btn=document.createElement("span");
        sql_close_btn.className="glyphicon glyphicon-remove pull-right";
        sql_close_btn.addEventListener("click",that.close);
        sql_w_top.appendChild(sql_close_btn);
        //-全选按钮
        var sql_allselect_btn = document.createElement("input");
        sql_allselect_btn.setAttribute("type","checkbox");
        sql_allselect_btn.checked=(!!this.ret&&this.ret.value!="")?false:true;
        sql_allselect_btn.addEventListener("click",that.selectAll)
        sql_w_top.appendChild(sql_allselect_btn);
        var sql_allselect_zh=document.createElement("span");
        sql_allselect_zh.innerHTML="全选";
        sql_w_top.appendChild(sql_allselect_zh);

        //选项窗口
        this.sql_w_mid=document.createElement("div");
        this.sql_w_mid.className="sql_window_mid";
        sql_w.appendChild(this.sql_w_mid)
        //-输入框
        var sql_input = document.createElement("input");
        sql_input.className="form-control keyvalue";
        sql_input.setAttribute("placeholder","搜索关键字");
        sql_input.value=(!!that.ret&&that.ret.value!="")?that.ret.value:"";
        this.sql_w_mid.appendChild(sql_input);
        //-按钮
        var sql_btn = document.createElement("button");
        sql_btn.className="btn-xs btn-primary";

        //-模糊搜索
        var mohu_btn=sql_btn.cloneNode(true);
        mohu_btn.innerHTML="模糊搜索";
        mohu_btn.addEventListener("click",function(){that.finish("like")})
        this.sql_w_mid.appendChild(mohu_btn)
        //-精确搜索
        var acc_btn=sql_btn.cloneNode(true);
        acc_btn.innerHTML="精确搜索";
        acc_btn.addEventListener("click",function(){that.finish("accuracy")})
        this.sql_w_mid.appendChild(acc_btn)
        //-大于搜索
        var more_btn=sql_btn.cloneNode(true);
        more_btn.innerHTML="大于此值";
        more_btn.addEventListener("click",function(){that.finish("more")})
        this.sql_w_mid.appendChild(more_btn)
        //-小于搜索
        var less_btn=sql_btn.cloneNode(true);
        less_btn.innerHTML="小于此值";
        less_btn.addEventListener("click",function(){that.finish("less")})
        this.sql_w_mid.appendChild(less_btn)
    }
    this.selectAll=function(){
        // console.dir(this);
        if(this.checked){
            that.finish("all");
        }

    }
    this.finish;
    this.close=function(){
        // alert(1);
        $(".sql_window_bg").remove();
        $(".sql_window_con").remove();

        // $(that.father).find("")
    }

}
function jt_child(){
    this.type="td";
    this.css;
    this.row=undefined;
    this.obj;
    this.create=function(){
        this.type=arguments[0];
        this.css=arguments[1];
        this.row=arguments[2];
        this.obj=document.createElement(this.type);
        this.obj.className=this.css;
        if(typeof(this.row)!="undefined"){
            this.obj.setAttribute("row",this.row)
        }

    }
}
//上传过滤
function post_filter(arr){
    var post_arr_type = typeof(arr);
    switch (post_arr_type) {
        case "string":
            if(arr == ""){
                return false;
            }
            break;
        case "undefined":
            console.log("输入的资料未定义")
            return false;
            break;
        case "object":
            for(var key in arr){
                var value = post_filter(arr[key]);
                if(!value){
                    return false;
                }
            }
    }
    return arr;
}
//呼叫提醒
function arm (str){
    str=(!str)?"数据为空":str;
    if(!debug){alert(str)};
    console.log(str)
}
//去除空格---函数法
//删除左右两端的空格
function trim(str){
       return str.replace(/(^\s*)|(\s*$)/g, "");
   }
//删除左边的空格
function ltrim(str){
    return str.replace(/(^\s*)/g,"");
}
//删除右边的空格
function rtrim(str){
    return str.replace(/(\s*$)/g,"");
}

jq 插件化 自消失消息提示

js

//arm信息提示模块
function arm(str,type,addition){
  var type=(typeof(type)=="undefined")?"":type;
  var life;
  switch (type) {
    case "warning":
      life=10000;
      break;
    case "danger":
      life="long"
      break;
    case "info":
      life=10000;
      break;
    default:
      type="default";
      life=10000;
  }
  ac=new armContant();
  ac.create(str,type,life,addition)
}
var armcount=0;
function armContant(){
  this.armid=++armcount;
  var that = this;

  this.color;
  this.life;
  this.text;
  this.addition;
  this.content;
  this.closebtn=function(){
    var span =document.createElement("span");
    span.innerHTML="X";
    span.className="arm_btn_close";
    span.addEventListener("click",that.close);
    return span;
  }
  this.colorArr={
    "warning":["#F2753F","#FFFC66"],
    "danger":["#D53627","#F5F6EB"],
    "info":["#57D2F7","#666"],
    "default":["#00C4AB","#fff"],
  };
  this.create=function(){
    that.text=arguments[0];
    that.color=that.colorArr[arguments[1]];
    that.life=arguments[2]
    that.addition=arguments[3];
    //大容器
    that.content=document.createElement("div");
    that.content.className="arm_bigcon";
    that.content.style.background=that.color[0];
    that.content.style.color=that.color[1];
    that.content.setAttribute("armid",that.armid);

    // 图标容器
    var imgIcon = document.createElement("div");
    // imgIcon.className = "arm_icon_logo";
    imgIcon.className = "arm_icon_logo";
    imgIcon.innerHTML = "小冰军机处";
    that.content.appendChild(imgIcon);

    //-文字容器
    var strcon=document.createElement("div");
    strcon.className="arm_con";
    that.content.appendChild(strcon);

    //--文字
    var span=document.createElement("span");
    span.className="arm_str_main";
    span.innerHTML=that.text;
    strcon.appendChild(span)

    //--额外内容
    if(!!that.addition){
      strcon.appendChild(that.addition);
    }
    //--关闭按钮
    that.content.appendChild(that.closebtn());

    document.body.appendChild(that.content);
    if(that.life!="long"){
      setTimeout(that.close,that.life);
    }

  }
  this.close=function(){
    $("[armid="+that.armid+"]").remove();
  }
}

css

@charset "UTF-8";
/*arm*/
.arm_bigcon{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
}
.arm_con{
  position: relative;
  margin: auto;
  left: 0;right: 0;
  top:0;
  padding:10px;
  width: 400px;
}
.arm_btn_close{
  position: absolute;
  margin: auto;
  top:0;bottom: 0;
  right:0;
  width: 20px;height:20px;
  cursor: pointer;
}
.arm_icon_logo{
  position: absolute;
  margin: auto;
  top:0;bottom: 0;
  left:0;
  line-height: 40px;
  height:40px;
  width:100px;
  padding:0 10px;
  /*background: url(../images/miniice.png) no-repeat;*/
  /*background-color: #fcfcfc;*/
  font-family: "microsoft yahei";
  background-position: center;
  background-size: 100% auto;

}

jq 插件化巨坑 loading 拷贝副本替换法

点哪个哪个显示加载

js

//调用
$(even).mini_load();//显示加载
$(even).mini_loaded();//回到原来的样子


$.fn.extend({
    mini_load:function(msg,color){
        var msg=(typeof(msg)=="undefined")?"操作中...":msg;
        var that=$(this);
        var that_copy=$(that).clone();
        var color=(typeof(color)=="undefined")?"white":"black";
        var img_load=document.createElement("span")
        img_load.className="span_loading";
        that_copy.attr("copy","loadingcopy");
        that_copy.html(msg);
        that_copy.prepend(img_load);
        $(that_copy).removeAttr("onclick");
        that.hide();
        that.after(that_copy);
    },
    mini_loaded:function(){
        var that=$(this);
        that.show();
        that.siblings("[copy='loadingcopy']").remove();
    }
})

css

.span_loading{
  background: url(../images/loading-white.gif);
  width:20px;
  height: 20px;
  display: inline-block;
  background-size: 100%;
  vertical-align:middle;
}

 

ajax 封装成 我喜欢的样子

需要jquery支持

//创建ajax类
function ajaxobj(){
  this.url="";
  this.data="";
  this.type="post";
  this.async=true;//true:同步     false:异步
  this.success;//成功时执行
    this.error;//失败时执行
  this.complete=function(XHR,TextStatus){//完成时执行
   if(XHR.statusText!="OK"){
            if(typeof this.error == "function"){this.error();}
            console.warn(that.url+"->"+XHR.statusText)
    }
  };
  this.timeout=120000;//120秒超时
  this.send=function(){
    $.ajax(this);
  }
}
function ajax(url,_post,callback,error){
      var _ajax = new ajaxobj();
      _ajax.url=url;
      _ajax.data=_post;
      _ajax.success=callback;
      _ajax.error=error;
      _ajax.send();
    }

 
原生js ajax
来源http://www.cnblogs.com/a757956132/p/5603176.html

/* 封装_ajax函数
 * @param {string}opt.type http连接的方式,包括POST和GET两种方式
 * @param {string}opt.url 发送请求的url
 * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
 * @param {object}opt.data 发送的参数,格式为对象类型
 * @param {function}opt.success ajax发送并接收成功调用的回调函数
 */
   function _ajax(opt) {
        opt = opt || {};
        opt.method = opt.method.toUpperCase() || 'POST';
        opt.url = opt.url || '';
        opt.async = opt.async || true;
        opt.data = opt.data || null;
        opt.success = opt.success || function () {};
        opt.error = opt.error|| function () {};
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }var params = [];
        for (var key in opt.data){
            params.push(key + '=' + opt.data[key]);
        }
        var postData = params.join('&');
        if (opt.method.toUpperCase() === 'POST') {
            xmlHttp.open(opt.method, opt.url, opt.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        }
        else if (opt.method.toUpperCase() === 'GET') {
            xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
            xmlHttp.send(null);
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
              opt.success(xmlHttp.responseText);
            }
            if(xmlHttp.readyState == 4 && xmlHttp.status != 200){
              opt.error(xmlHttp);
              console.warn(`[${opt.method}]${opt.url} -> ${xmlHttp.status}-${xmlHttp.statusText}`)
            }
        };
    }
        /**
        * 我喜欢的样子
        */
    function ajax(url,_post,callback,error){
      _ajax({
        method: 'POST',
        url: url,
        data: _post,
        success: function (response) {
           callback(response);
        },
        error: error
    });
    }

js trim类 去除字符串空格

类方法

//去除左右空格
String.prototype.trim=function(){
   return this.replace(/(^\s*)|(\s*$)/g, "");
}
//去除左空格
String.prototype.ltrim=function(){
   return this.replace(/(^\s*)/g,"");
}
//去除右空格
String.prototype.rtrim=function(){
   return this.replace(/(\s*$)/g,"");
}

函数

function trim(str){ //删除左右两端的空格
       return str.replace(/(^\s*)|(\s*$)/g, "");
   }
   function ltrim(str){ //删除左边的空格
       return str.replace(/(^\s*)/g,"");
   }
   function rtrim(str){ //删除右边的空格
       return str.replace(/(\s*$)/g,"");
   }

 

 

bootstrap js创建模态框

Modal 属性

**m_系列——文字描述、内容类

//模态框抬头标题

Modal.m_title="string";

//模态框内容区域

Modal.m_body="string";//支持html对象

//模态框id

Modal.m_id="string";

**set_系列——执行函数类

//生成模态框底部按钮

Modal.set_btn({"string":callback})//按钮文字、执行函数

**基础系列

//弹出模态框

Modal.create()

//关闭模态框

Modal.close()

//模态框
function CreateModal(){
  this.m_title="默认模态框";
  this.m_body="默认内容";
  this.m_id="newmodal";
  this.m_target="body";
  this.btn=[];
  this.set_btn=function(data){
    var btnarr=[];
    for(var key in data){
      var btn = document.createElement("button");
      btn.className="btn btn-primary";
      btn.onclick=data[key];
      btn.innerHTML=key;
      this.btn.push(btn);
    }
  }
  this.close=function(){
    $(".modal.fade").remove();
    $(".modal-backdrop.fade").remove();
  }
  this.create=function(){
    this.close();
    var modal_block = document.createElement("div");
      modal_block.className = "modal fade";
      modal_block.id = this.m_id;
      modal_block.setAttribute("data-show","true")
      var modal_dialog = document.createElement("div");
        modal_dialog.className="modal-dialog modal-lg";
        var modal_content = document.createElement("div");
          modal_content.className="modal-content";
          var modal_head = document.createElement("div");
            modal_head.className=  "modal-header";
            var btn_close = document.createElement("button");
              btn_close.className="close";
              btn_close.type="button";
              btn_close.innerHTML="&times;";
              btn_close.addEventListener("click",this.close);
            modal_head.appendChild(btn_close);
            var modal_head_p = document.createElement("h4");
              modal_head_p.innerHTML=this.m_title;
            modal_head.appendChild(modal_head_p);
          modal_content.appendChild(modal_head);
          var modal_body = document.createElement("div");
            modal_body.className="modal_body";
            if(typeof(this.m_body)=="string"){
              modal_body.innerHTML=this.m_body;
            }else{
              modal_body.appendChild(this.m_body);
            }
          modal_content.appendChild(modal_body);
          var modal_footer =document.createElement("div");
            modal_footer.className="modal-footer";
            this.btn.map(function(btns,index){
              modal_footer.appendChild(btns);
            })
          modal_content.appendChild(modal_footer);
        modal_dialog.appendChild(modal_content);
      modal_block.appendChild(modal_dialog);

    $(this.m_target).append(modal_block);
    $("#"+this.m_id).modal('show');
  }
}

 

 

【css公用库】弹窗

css

/*===========================================弹出表单式弹窗*/
.popur-bg{/*渐变背景*/
	width:100%;
	height:100%;
	position:fixed;
	top:0;
	left:0;
	background:rgba(0,0,0,.2);
	transition: all 0.4s ease-in-out 0s;
    display: flex;
    justify-content: center;
    align-items: center;
}
.popur-bg:hover{
	background:rgba(0,0,0,.4);
}
.popur-form{/*表框外形*/
	width:80%;
	height:70%;
	background:#fff;
	display: flex;
	flex-flow:column nowrap;
	align-items:center;
    justify-content: space-between;
}
.popur-form:hover {/*表框外形*/
    box-sizing: inherit;
}
.popur-form-m{
	max-height:70%;
}
.popur-form-sm{
	min-height:150px;
}
.popur-form-lg{
	width:100%;
	height:100%;
}
.popur-form-lg .popur-form-body{
	max-height:80% !important;
}
.popur-form-title{
	line-height:40px;
	font-size:18px;
	width:80%;
	text-align:center;
	border-bottom:1px solid #2ABBAE;
	margin-bottom:10px;
}
.popur-form-body{
	width:100%;
	max-height:70%;
	display:flex;
	flex-grow:2;
    flex-flow: column nowrap;
    align-items: center;
    overflow-y:auto;
}
.popur-form-body p{
	color:#999;
}
.p-f-b-tr{
	width:80%;
	display:flex;
    flex-flow: column nowrap;
    flex:none;
}
.p-f-b-tr > p{
	width: 100%;
    text-align: center;
    margin: 3px 0;
    display:flex;
    align-items:center;
    font-size:0.6em;
}
.p-f-b-tr > :not(p){
	width:100%;
}
.p-f-b-tr [type=text],.p-f-b-tr [type=number]{
	border:none;
	border-bottom:1px solid #838da5;
}
.popur-form-footer{
	margin:10px 0;
	width:100%;
	display:flex;
	justify-content:space-around;
	flex-shrink:0
}

 

js

/*===========================================通用弹窗-表单型(需要printf)*/
/*var trans={"t_id":["系统ID","text"],
			           "t_loginname":["用户名","input"],
			           "t_password":["密码","input"],
			           "t_name":["姓名","input"],
			           "t_tel":["手机号码","input"],
			           "t_email":["E-mail","input"],
			           "t_status":["账号状态","switch"],
			           "t_note":["Note","input"],
			           "t_last_login_time":["上次登陆时间","text"],
			           "t_login_ip":["IP","text"]

			           };
			var Jalert_body_str="";
			var Jalert_body=datacache.map(function(e,index){
				if(e['t_id']==itid){
					for(var value in trans){
						var filter = (e[value]==null)?"":e[value];
						Jalert_body_str+=Jtable_td(trans[value][1],trans[value][0],value,filter,roleSelectArr);
					}
				}
			});
			var Jalert_footer=
				"<button type='button' class='xbtn xbtn-white' onclick='Jalert_close(this)'>"+
					"关闭"+
				"</button>";
			$("body").append(Jalert('详情',Jalert_body_str,Jalert_footer,'m'));
 * */
var pupur_str=("<div class='popur-bg'>"+
	"<div class='popur-form popur-form-{3}'>"+
		"<div class='popur-form-title'>{0}</div>"+
		"<div class='popur-form-body'>"+
		"{1}"+
		"</div>"+
		"<div class='popur-form-footer'>"+
			"{2}"+
		"</div>"+
	"</div>"+
"</div>");
function Jalert(tit,body,foot,type){
	type=(typeof(type)=="undefined")?"m":type;

	return printf(pupur_str,tit,body,foot,type);

}
function Jalert_close(even){
	$(".popur-bg").remove();
	$("body").css("overflow","auto");
}
function BodyNoScoller(){
	document.querySelector('.popur-bg').addEventListener('touchmove',function(e){
        document.body.style.overflow = 'hidden';
    },false);
}
/*===========================================表格内容生成*/
function Jtable_td(type,title,envalue,value,addition){
	var con;
	var value=(value==""||value==null||typeof(value)=="undefined")?" ":value;
	switch (type){
	case "select":
		con="<div class='p-f-b-tr'>"+
		"<p>"+title+"</p>"+
		"<select name='"+envalue+"' class='"+envalue+"'>";
		for(var jvalue in addition){
			con+=("<option rowx_index='"+jvalue+"' "+
					((addition[jvalue]==envalue)?"selected":"")+">"+
					addition[jvalue]+
					"</option>");
		}
		con+="</select></div>"
		break;
	case "input":
		con="<div class='p-f-b-tr'>"+
			"<p>"+title+"</p>"+
			"<input type='text' name='"+envalue+"' class='"+envalue+"' value='"+value+"'></div>";
		break;
	case "number":
		con="<div class='p-f-b-tr'>"+
		"<p>"+title+"</p>"+
		"<input type='number' name='"+envalue+"' class='"+envalue+"' value='"+value+"'></div>";
		break;
	case "textarea":
		con="<div class='p-f-b-tr'>"+
		"<p>"+title+"</p>"+
		"<textarea  class='"+envalue+"' name='"+envalue+"' value='"+value+"'></textarea></div>";
		break;
	case "switch":
		value=(value=="")?"1":value;
		con="<div class='p-f-b-tr'>"+
		"<p>"+title+"</p>"+
		"<p>"+
		"<button class='switch "+((value==1)?"switch-on":"")+" "+envalue+"' statu='"+value+"' onclick='switch_change(this)'>"+
		"<i class='switch-btn'></i><p>"+((value==1)?"正常":"关闭")+"</p>"+
		"</button></p></div>"
		break;
	default:
		con="<div class='p-f-b-tr'>"+
			"<p>"+title+"</p>"+
			"<span class='"+envalue+"' name='"+envalue+"'>"+value+"</span></div>"
		break;
	}

	return con;
};
/*===========================================简单实现printf功能*/
function printf() {
  var num = arguments.length;
  var oStr = arguments[0];
  for (var i = 1; i < num; i++) {
    var pattern = "\\{" + (i-1) + "\\}";
    var re = new RegExp(pattern, "g");
    oStr = oStr.replace(re, arguments[i]);
  }
  return oStr;
}