基于JavaScript实现函数常用方法

/**
* 弹出加载层
*/
function pageload() {
    $("
").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body"); $("
").html("正在操作,请稍候。。。").appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 }); } /** * 弹出加载层 */ function pageloadms(ms) { $("
").css({ display: "block", width: "100%","z-index":"10000", height: $(window).height() }).appendTo("body"); $("
").html(ms).appendTo("body").css({ display: "block", "z-index": "10000", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 }); } /** * 取消加载层 */ function dispageload() { $(".datagrid-mask").remove(); $(".datagrid-mask-msg").remove(); $(".easyui-progressbar").remove(); } /** * 进度条圆形... */ function pageLoadDown() { var html = "下载中....
0%
"; $("
").css({ display: "block", width: "100%", "z-index": "10000", height: $(window).height() }).appendTo("body"); $("
").html(html).appendTo("body").css({ display: "block", "z-index": "10000", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 }); } /** * 进度条长条... */ function pageLoadBarDownFile(progressBarId) { progressBarId = progressBarId || _progressBarIdInfo; var _width = $(window).width() / 2; var html = "
"; $("
").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body"); $(html).appendTo("body").css({ display: "block", height: '10%', background: 'white', width: '50%', position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, margin: 'auto', left: 0 }); $('#' + progressBarId).progressbar({ value: 0, height: 20 }); } /** * 圆环进度 */ var _changeProcess = function (value) { $('.mask span').html(value); var num = value * 3.6; if (num < 180) { $('.rightcompress').css('transform', 'rotate(' + num + 'deg)'); } else { $('.rightcompress').css('transform', 'rotate(180deg)'); $('.leftcompress').css('transform', 'rotate(' + (num - 180) + 'deg)'); }; }; /** * 阻止函数 */ function prevent_reloading() { var pendingRequests = {}; jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) { var key = options.url; if (!pendingRequests[key]) { pendingRequests[key] = jqXHR; } else { //jqXHR.abort(); //放弃后触发的提交 pendingRequests[key].abort(); // 放弃先触发的提交 } var complete = options.complete; options.complete = function (jqXHR, textStatus) { pendingRequests[key] = null; if (jQuery.isFunction(complete)) { complete.apply(this, arguments); } }; }); } /** * 有阻止函数弹出层 */ function pageLoading(ms) { prevent_reloading(); if (ms) { pageloadms(ms); } else { pageload(); } } /** * 文件下载中... */ function pageLoadDownFile() { var html = "
0%
"; $("
").css({ display: "block", width: "100%", "z-index": "10000", height: $(window).height() }).appendTo("body"); $("
").html(html).appendTo("body").css({ display: "block", "z-index": "10000", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 }); } /** * 圆环进度(小) */ var _changeFileProcess = function (value) { $('.maskfile span').html(value); var num = value * 3.6; if (num < 180) { $('.rightfile').css('transform', 'rotate(' + num + 'deg)'); } else { $('.rightfile').css('transform', 'rotate(180deg)'); $('.leftfile').css('transform', 'rotate(' + (num - 180) + 'deg)'); }; }; axios.interceptors.request.use(function (config) { config.headers['X-Requested-With'] = 'XMLHttpRequest'; return config; }); axios.interceptors.response.use(function (response) { return response; }, function (error) { if (error.response) { if (error.response.status === 800) { var _resData = error.response.data; if (_resData.ErrAjaxState && _resData.ErrAjaxState === "0") { return Promise.reject(_resData.ErrAjaxMessage); } return Promise.reject(error); } return Promise.reject(error); } return Promise.reject(error); });
function dgpageInit(id) {

    var _data = $('#' + id).data('datagrid');
    $('#' + id).datagrid('resize', { width: '100%' });
    var firsetPageSize = _data.options.pageSize;
    var arryPageList = [firsetPageSize, 20, 30, 50, 100, 200, 500, 1000];
    $.unique(arryPageList.sort(function (a, b) {
        return a - b;
    }));

    var p = $('#' + id).datagrid('getPager');
    $(p).pagination({
        beforePageText: '第',
        afterPageText: '页    共 {pages} 页',
        displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
        pageSize: firsetPageSize,
        pageList: arryPageList,
        onBeforeRefresh: function () {
            $(this).pagination('loading');

            $(this).pagination('loaded');
        }
    });
}

function mergeCells(dg, data, cellnames) {
    for (var i = 0; i < cellnames.length; i++) {
        var cellname = cellnames[i];
        var merges = [];
        for (var r = 0; r < data.rows.length; r++) {
            var row = data.rows[r];
            var mergeinfo = new Object();
            var nr = row[cellname];
            var rowspan = 1;
            for (var r1 = r + 1; r1 < data.rows.length; r1++) {
                var row1 = data.rows[r1];
                var nr1 = row1[cellname];

                if (nr1 && nr1 == nr && nr1 != "") {
                    mergeinfo.index = r;
                    rowspan++;
                    mergeinfo.rowspan = rowspan;
                }
                else {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                    break;
                }
                if (r1 == data.rows.length - 1) {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                }
            }
        }
        for (var j = 0; j < merges.length; j++) {
            $('#' + dg).datagrid('mergeCells', {
                index: merges[j].index,
                field: cellname,
                rowspan: merges[j].rowspan
            });
        }
    }
}

function mergeCells_table(dg, data, cellnames) {
    var table = document.getElementById(dg);
    for (var i = 0; i < cellnames.length; i++) {
        var cellname = cellnames[i];
        var merges = [];
        for (var r = 0; r < data.rows.length; r++) {
            var row = data.rows[r];
            var mergeinfo = new Object();
            var nr = row[cellname];
            var rowspan = 1;
            for (var r1 = r + 1; r1 < data.rows.length; r1++) {
                var row1 = data.rows[r1];
                var nr1 = row1[cellname];

                if (nr1 && nr1 == nr && nr1 != "") {
                    mergeinfo.index = r;
                    rowspan++;
                    mergeinfo.rowspan = rowspan;
                    table.rows[r + 1].cells[i].rowSpan = rowspan;
                    table.rows[r1 + 1].cells[i].style.display = "none";
                }
                else {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                    break;
                }
                if (r1 == data.rows.length - 1) {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                }
            }
        }
    }
}

function mergeCells_table1(dg, data, cellnames,cellindexs) {
    var table = document.getElementById(dg);
    for (var i = 0; i < cellnames.length; i++) {
        var cellname = cellnames[i];
        var merges = [];
        for (var r = 0; r < data.rows.length; r++) {
            var row = data.rows[r];
            var mergeinfo = new Object();
            var nr = row[cellname];
            var rowspan = 1;
            for (var r1 = r + 1; r1 < data.rows.length; r1++) {
                var row1 = data.rows[r1];
                var nr1 = row1[cellname];

                if (nr1 && nr1 == nr && nr1 != "") {
                    mergeinfo.index = r;
                    rowspan++;
                    var cellindex = cellindexs[i];
                    mergeinfo.rowspan = rowspan;
                    table.rows[r + 1].cells[cellindex].rowSpan = rowspan;
                    table.rows[r1 + 1].cells[cellindex].style.display = "none";
                }
                else {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                    break;
                }
                if (r1 == data.rows.length - 1) {
                    if (rowspan > 1) {
                        merges.push(mergeinfo);
                        r = r1 - 1;
                    }
                }
            }
        }
    }
}

//cellcomp列相同,cellnames合并
function mergeCells_one(dg, data, cellcomp, cellnames) {
    var merges = [];
    for (var r = 0; r < data.rows.length; r++) {
        var row = data.rows[r];
        var mergeinfo = new Object();
        var nr = row[cellcomp];
        var rowspan = 1;
        for (var r1 = r + 1; r1 < data.rows.length; r1++) {
            var row1 = data.rows[r1];
            var nr1 = row1[cellcomp];

            if (nr1 && nr1 == nr && nr1 != "") {
                mergeinfo.index = r;
                rowspan++;
                mergeinfo.rowspan = rowspan;
            }
            else {
                if (rowspan > 1) {
                    merges.push(mergeinfo);
                    r = r1 - 1;
                }
                break;
            }
            if (r1 == data.rows.length - 1) {
                if (rowspan > 1) {
                    merges.push(mergeinfo);
                    r = r1 - 1;
                }
            }
        }
    }
    for (var i = 0; i < cellnames.length; i++) {
        var cellname = cellnames[i];
        for (var j = 0; j < merges.length; j++) {
            $('#' + dg).datagrid('mergeCells', {
                index: merges[j].index,
                field: cellname,
                rowspan: merges[j].rowspan
            });
        }
    }
}

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};  


/**
* 设置未来(全局)的AJAX请求默认选项
* 主要设置了AJAX请求遇到Session过期的情况
*/
$.ajaxSetup({
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    complete: function (XMLHttpRequest, textStatus) {
        //通过XMLHttpRequest取得响应头,sessionstatus,
        var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
        var loginurl = XMLHttpRequest.getResponseHeader("loginurl");
        if (sessionstatus == "timeout") {
//            alert("由于您长时间没有操作, session已过期, 请重新登录.");
            var top = getTopWinow();
            top.location.href = loginurl;
        }
    }
});
 
/**
* 在页面中任何嵌套层次的窗口中获取顶层窗口
* @return 当前页面的顶层窗口对象
*/
function getTopWinow() {
    var p = window;
    while (p != p.parent) {
        p = p.parent;
    }
    return p;
}

function isNumber(str) {
    var reg = /^[0-9]*[1-9][0-9]*$/;
    return reg.test(str);
}

function isEmail(str) {
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
    return reg.test(str);
}

//护照
function isPassport(str) {
    var reg = /^[a-zA-Z0-9]{3,21}$/;
    return reg.test(str);
}
//港澳回归证和台胞证
function isZjGat(str) {
    var reg = /^[a-zA-Z0-9]{5,21}$/;
    return reg.test(str);
}
//外国人居留许可证
function isPermit(str) {
    var reg = /^[a-zA-Z]{3}\d{12}$/;
    return reg.test(str);
}

//全选与反选共用 
function check_all(inputcheck, strid) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (inputs[i].id.indexOf(strid) != -1)
                inputs[i].checked = document.getElementById(inputcheck).checked;
        }
    }
}

function txtNumKeyPress(txt) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (typeof ($.browser) != "undefined" && !$.browser.msie && (event.keyCode == 0x8))   // if firefox
    {
        return;
    }
    
    event.returnValue = code >= 48 && code <= 57 || event.keyCode == 46;  // number or dot 
}

function txtNumblur(txt) {
    if (isNaN(txt.value)) {
        txt.value = "";
    }
    if (txt.value.lastIndexOf(".") == (txt.value.length - 1)) {
        txt.value = txt.value.substr(0, txt.value.length - 1);
    }
    if (txt.value.indexOf(".") > 0) {
        txt.value = txt.value.substr(0, txt.value.indexOf(".") + 2);
    }
    if (parseFloat(txt.value) > 100) {
        txt.value = "100";
    }
}


//文本框禁止粘贴操作 onkeydown="fncKeyStop(event)" onpaste="return false"
function fncKeyStop(evt) {
    if (!window.event) {
        var keyhh = window.event ? event.keyCode : event.which;
        var keycode = keyhh;
        var key = String.fromCharCode(keycode).toLowerCase();
        if (evt.ctrlKey && key == "v") {
            evt.preventDefault();
            evt.stopPropagation();
        }
    }
}


//Javascript正则控制文本框只能输入整数或浮点数onkeyup="CheckInputIntFloat(this)" 
function CheckInputIntFloat(oInput) {
    if ('' != oInput.value.replace(/\d{1,}\.{0,1}\d{0,}/, '')) {
        oInput.value = oInput.value.match(/\d{1,}\.{0,1}\d{0,}/) == null ? '' : oInput.value.match(/\d{1,}\.{0,1}\d{0,}/);
    }
    if ("" != oInput.value) {
        if (oInput.value.indexOf('.') <= -1) {
            if (oInput.value.length > 3) {
                oInput.value = '';
            }
        } else {
            var strs = new Array(); //定义一数组 
            strs = oInput.value.split('.'); //字符分割
            if (strs[0].toString().length > 2) {
                oInput.value = '';
            }
            if (oInput.value.length > 5) {
                oInput.value = '';
            }

        }
    }
}

/** 
* 扩展combox验证,easyui原始只验证select text的值,不支持value验证 
*/
$.extend($.fn.validatebox.defaults.rules, {
    comboxValidate: {
        validator: function (value, param, missingMessage) {
            try {
                if ($('#' + param).combobox('getValue') != '' && $('#' + param).combobox('getValue') != null) {
                    return true;
                }
                return false;
            }
            catch (ex) {
                //$('#' + param).val("");
                return false;
            }
        },
        message: "{1}"
    }
});


function responseTextTitle(responseText)
{
    var index1 = responseText.indexOf("");
    var index11 = responseText.indexOf("<TITLE>");
    index1 = index1 > index11 ? index1 : index11;
    var index2 = responseText.indexOf("");
    var index22 = responseText.indexOf("");
    index2 = index2 > index22 ? index2 : index22;
    if (index1 > 0 && index2>0) {
        return responseText.substring(index1 + 7, index2);
    }
    else {
        return responseText;
    }
}

//aes加密
String.prototype.AESEncrypt = function () {
    var key = CryptoJS.enc.Utf8.parse("8NONwyJtHesysWpM"); //8NONwyJtHesysWpM
    var realcontent = this.toString();
    var encontent = CryptoJS.AES.encrypt(realcontent, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    var encryptedData = encontent.ciphertext.toString()
    return encryptedData;
}

String.prototype.trim = function () {
    var restr = this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
    return restr;
}

String.prototype.getParamvalueBykey = function (key) {
    var reg = new RegExp("" + key + "=([^&]*)")
    var urlstr = this.toString();
    var mathresult = reg.exec(this.toString());
    if (mathresult != null)
        return mathresult[1];
    else
        return "";
}

/** 
* 获取字符串长度
*/
String.prototype.pointLength = function () {
    var len = 0;
    for (var i = 0; i < this.length;) {
        var codePoint = this.codePointAt(i);
        i += codePoint > 0xffff ? 2 : 1;
        len++;
    }
    return len;
}

/** 
* 获取字符串某个位置字符
*/
String.prototype.pointAt = function (index) {
    var curIndex = 0;//码点的下标
    for (var i = 0; i < this.length;) {
        var codePoint = this.codePointAt(i);
        if (curIndex === index) {
            return String.fromCodePoint(codePoint);
        }
        i += codePoint > 0xffff ? 2 : 1;
        curIndex++;
    }
}

/** 
* 获取字符串截取
*/
String.prototype.sliceByPoint = function (start, end) {
    if (start === undefined) start = 0;
    if (end === undefined) end = this.pointLength();
    var result = '';
    for (var i = start; i < end; i++) {
        result += this.pointAt(i);
    }
    return result;
}

/**
*是否Object对象
*@param val 值
*@return boolean
*/
jQuery.isObject = function (val) {
    if (typeof val === 'object' && val !== null) {
        return true;
    }
    return false;
}

/**
*是否相同
*@param val1 第一个值
*@param val2 第二个值
*@return boolean
*/
jQuery.isEquals = function (val1, val2) {
    if ($.isObject(val1) && $.isObject(val2)) {
        var keys1 = Object.keys(val1);
        var keys2 = Object.keys(val2);
        if (keys1.length !== keys2.length) {
            return false;
        }
        for (var i = 0; i < keys1.length; i++) {
            if (keys2.indexOf(keys1[i]) < 0) {
                return false;
            }
            if (!$.isEquals(val1[keys1[i]], val2[keys1[i]])) {
                return false;
            }
        }
        return true;
    } else {
        return val1 === val2;
    }
}

/**
*数组去重
*@param {Array} arr
*@return {Array}
*/
jQuery.uniqueArray = function (arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        var isFind = false;
        for (var j = 0; j < result.length; j++) {
            if ($.isEquals(result[j], arr[i])) {
                isFind = true;
                break;
            }
        }
        if (!isFind) {
            result.push(arr[i]);
        }
    }
    return result;
}

/**
*深度克隆
*@param value
*@return value
*/
jQuery.deepClone = function (value) {
    var cache = new WeakMap();
    function _deepClone(value) {
        if (typeof value !== 'object' || value === null) {
            return value;
        }
        if (cache.has(value)) {
            return cache.get(value);
        }
        var result = Array.isArray(value) ? [] : {};
        Object.setPrototypeOf(result, Object.getPrototypeOf(value));
        cache.set(value, result);
        for (key in value) {
            if (value.hasOwnProperty(key)) {
                result[key] = _deepClone(value[key]);
            }
        }
        return result;
    }
    return _deepClone(value);
}

/**
*深度克隆(拷贝)为与源码的下标对应上,我们把第一个参数称为`第0个参数`,依次类推
*@param 待克隆的对象
*@return 克隆的对象
*@example $.deepCopyClone(columnsxx, columns);
*/
jQuery.deepCopyClone = jQuery.fn.extend = function () {
    var options,
	 	name,
	 	src,
	 	copy,
	 	copyIsArray,
	 	clone,
	    target = arguments[0] || {}, // 默认第0个参数为目标参数
	 	i = 1, // i表示从第几个参数开始将目标参数与其进行合并,默认从第1个参数开始向第0个参数进行合并
	 	length = arguments.length,
		deep = false; // 默认为浅拷贝

    // 判断第0个参数的类型,若第0个参数是boolean类型,则获取其为true还是false
    // 同时将第1个参数作为目标参数,i从当前目标参数的下一个
    // Handle a deep copy situation
    if (typeof target === "boolean") {
        deep = target;

        // Skip the boolean and the target
        // 如果第一个参数是Boolean类型
        target = arguments[i] || {};
        i++;
    }

    // 判断目标参数的类型,若目标参数既不是object类型,也不是function类型,则为目标参数重新赋值空对象
    // Handle case when target is a string or something (possible in deep copy)
    if (typeof target !== "object" && !jQuery.isFunction(target)) {
        target = {};
    }

    // 若目标参数后面没有参数了,如$.extend({_name:'wenzi'}), $.extend(true, {_name:'wenzi'})
    // 则目标参数即为jQuery本身,而target表示的参数不再为目标参数
    // Extend jQuery itself if only one argument is passed
    if (i === length) {
        target = this;
        i--;
    }

    // 从第i个参数开始遍历
    for (; i < length; i++) {
        // 获取第i个参数,且该参数不为null和undefind,在js中null和undefined,如果不区分类型,是相等的,null==undefined为true,
        // 因此可以用null来同时过滤掉null和undefind
        // 比如$.extend(target, {}, null);中的第2个参数null是不参与合并的
        // Only deal with non-null/undefined values
        if ((options = arguments[i]) != null) {

            // 使用for~in获取该参数中所有可枚举的属性
            // Extend the base object
            for (name in options) {
                src = target[name]; // 目标参数中name字段的值
                copy = options[name]; // 当前参数中name字段的值,有可能是值,Object,Array

                // 若参数中属性的值就是目标参数,停止赋值,进行下一个字段的赋值
                // 这是为了防止无限的循环嵌套,我们把这个称为,在下面进行比较详细的讲解
                // Prevent never-ending loop
                if (target === copy) {
                    continue;
                }

                // 若deep为true,且当前参数中name字段的值存在且为object类型或Array类型,则进行深度赋值
                // Recurse if we're merging plain objects or arrays
                // jQuery.isPlainObject()返回值为Boolean类型,如果指定的参数是纯粹的对象,则返回true,否则返回false
                if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
                    // 若当前参数中name字段的值为Array类型
                    // 判断目标参数中name字段的值是否存在,若存在则使用原来的,否则进行初始化
                    if (copyIsArray) {
                        //被复制的属性的值类型为Array
                        copyIsArray = false;
                        //判断该字段在target对象是否存在,存在且为Array,则直接使用原对象,否则创建空的Array
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        // 被复制的属性的值得类型为Object
                        //判断该字段在target对象是否存在,若存在且为Object则直接使用,否则创建空的Object
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // 递归处理,此处为2.2
                    // Never move original objects, clone them  
                    target[name] = jQuery.extend(deep, clone, copy);

                    // deep为false,则表示浅度拷贝,直接进行赋值
                    // Don't bring in undefined values
                } else if (copy !== undefined) {
                    // 若copy是简单的类型且存在值,则直接进行赋值
                    // 若原对象存在name属性,则直接覆盖掉;若不存在,则创建新的属性
                    target[name] = copy;
                }
            }
        }
    }

    // 返回修改后的目标参数
    // Return the modified object
    return target;
};

/**
*审核流程展示条
*/
jQuery.getShlInfoxx = function (shjl) {
    var html = "";
    var shz = true;
    $.each(shjl, function (i, o) {
        html += '
  • '; if (o.shljb == "0") { if (o.shsj != "") { html += '
    ' + o.shlmc + ' ' + o.shsj + ''; } else { shz = false; html += '
    ' + o.shlmc + ' 等待提交…'; } } else { if (o.shsj != "" && o.shlzt > 0) { html += '
    ' + o.shlmc + ' ' + o.shsj + ''; } else if (o.shsj != "" && o.shlzt < 0) { html += '
    ' + o.shlmc + ' ' + o.shsj + ''; } else { if (shz) { html += '
    ' + o.shlmc + ' 审核中…'; shz = false; } else { html += '
    ' + o.shlmc + ' 等待审核…'; } } } html += '
  • '; }); $("#step_sm").html(html); } /** *审核流程展示条(带驳回理由&&不通过理由) */ jQuery.getShlReasonInfoxx = function (shjl) { var html = ""; var shz = true; var sfjs = false; $.each(shjl, function (i, o) { html += '
  • '; if (o.shljb == "0") { var bhyjxx = ""; if (o.shyj && o.shyj != "") { bhyjxx = "
    (驳回理由:" + o.shyj + ")"; } if (o.shsj != "") { html += '
    ' + o.shlmc + bhyjxx + ' ' + o.shsj + ''; } else { shz = false; html += '
    ' + o.shlmc + bhyjxx + ' 等待提交…'; } } else { if (o.shsj != "" && o.shlzt > 0) { html += '
    ' + o.shlmc + ' ' + o.shsj + ''; } else if (o.shsj != "" && o.shlzt < 0) { sfjs = false; var fkli = ""; if (o.shyj && o.shyj != "") { fkli = "    (理由:" + o.shyj + ")"; } html += '
    ' + o.shlmc + fkli + ' ' + o.shsj + ''; } else { if (shz && sfjs) { html += '
    ' + o.shlmc + ' 审核中…'; shz = false; } else { html += '
    ' + o.shlmc + ' 等待审核…'; } } } html += '
  • '; }); $("#step_sm").html(html); } /** *审核流程展示条 */ jQuery.getShlProcess = function (shjl, isrea) { if (isrea) { $.getShlReasonInfoxx(shjl); } else { $.getShlInfoxx(shjl); } } /** * 时间控件格式化 * @param { String } target 控件ID * @param { String } datefromt 时间格式 * @return { String } date 时间 * @example inputEvents:$.myPluginWdatePickerDateFromt('wcnd','yyyy-MM-dd')" */ jQuery.myPluginWdatePickerDateFromt = function (target, datefromt) { if (!datefromt) datefromt = "yyyy-MM-dd HH:mm:ss"; var handle = $.extend({}, $.fn.textbox.defaults.inputEvents, { click: function () { WdatePicker({ onpicking: function (dp) { $("#" + target).textbox('setValue', dp.cal.getNewDateStr()); }, dateFmt: datefromt, onclearing: function (dp) { $("#" + target).textbox('setValue', ''); } }); WdatePicker({ onpicking: function (dp) { $("#" + target).textbox('setValue', dp.cal.getNewDateStr()); }, dateFmt: datefromt, onclearing: function (dp) { $("#" + target).textbox('setValue', ''); } }); } }); return handle; } /** * 函数管道,管道是将一个函数的输出直接发送到另一个函数 */ jQuery.myPluginPipeLine = function () { var args = Array.from(arguments); return function (val) { return args.reduce(function (result, func) { return func(result); }, val); } } /** * 柯里化函数,把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术 */ jQuery.myPluginCurrying = function (func) { var args = Array.prototype.slice.call(arguments, 1); //得到从下标1开始的参数 var that = this; return function () { var curArgs = Array.from(arguments); //当前调用的参数 var totalArgs = args.concat(curArgs); if (totalArgs.length >= func.length) { return func.apply(null, totalArgs); //参数数量够了 } else { //参数数量不够 totalArgs.unshift(func); return $.myPluginCurrying.apply(that, totalArgs); } } } var _layerWidth = ($(window).width() + 100) + "px"; var _layerHeight = ($(window).height() + 80) + "px"; /** * 获取datagrid的索引 */ jQuery.myPluginRowIndex = function (target) { var tr = $(target).closest('tr.datagrid-row'); return parseInt(tr.attr('datagrid-row-index')); } /** *弹出框信息,传入最少3个参数 *@param { String } _target this获取的元素 *@param { String } _dg *@param { String } _url *@param { String } _title *@param { Function } _fn *@param { Object } _objdata *@example $.myPluginOpenLayer(target, 'dg', url, '查看', info, research);$.myPluginOpenLayer(target, 'dg', url, '查看');$.myPluginOpenLayer('dg', url, '查看'); */ jQuery.myPluginOpenLayer = function () { var args = Array.from(arguments); var _argsLength = args.length; if (_argsLength < 3) { throw new Error("At least three input parameters"); } var _target = args[0]; var _dg = args[1]; var _url = args[2]; var _title = args[3]; var _fn = args[_argsLength - 1]; var _objdata = args[_argsLength - 2]; if (typeof _target !== 'object') { _target = null; _dg = args[0]; _url = args[1]; _title = args[2]; } var _parameter = ""; if (typeof _objdata === 'object' && _objdata !== null) { if (_target) { var _thisindex = $.myPluginRowIndex(_target); var _row = $("#" + _dg).datagrid('getRows')[_thisindex]; $.each(_objdata, function (kk, vv) { _parameter += ((vv == "" ? (kk + "=" + _row[kk]) : (kk + "=" + vv))) + "&"; }); } else { $.each(_objdata, function (kk, vv) { _parameter += (kk + "=" + vv + "&"); }); } } if (_parameter != "") { _parameter = _parameter.slice(0, -1); _url = _url + "?" + _parameter; } parent.layer.open({ type: 2, title: _title, area: [_layerWidth, _layerHeight], content: [_url], resize: true, maxmin: true, shadeClose: false, closeBtn: 1, end: function () { if (typeof _fn === "function") { _fn(); } } }); } /** *函数重载 *@example var getuser = $.createOverload(); *getuser.addImpl('number', function (number) { console.log('number'); }); *getuser.addImpl('string', 'string', function (naem, sex) { console.log('two'); }); */ jQuery.createOverload = function () { var callmap = new Map(); function overload() { var args = Array.from(arguments); var key = args.map(function (arg) { return typeof arg; }).join(','); var fn = callmap.get(key); if (fn) { return fn.apply(this, args); } else { throw new Error("no matching function"); } } overload.addImpl = function () { var args = Array.from(arguments); var fn = args.pop(); if (typeof fn !== 'function') { return; } var types = args; callmap.set(types.join(','), fn); } return overload; } /** *是否JSON字符 *@param { String } str *@example $.isJsonCharacter(str) */ jQuery.isJsonCharacter = function (str) { if (typeof str === 'string') { try { var obj = JSON.parse(str); if (typeof obj === 'object' && obj) { return true; } else { return false; } } catch (e) { return false; } } } /** *Bind函数 *@param { String,Number,Object } this指向 @return { Function } function *@example fn.myPluginBind('ctx',1,2); */ Function.prototype.myPluginBind = function (ctx) { var args = Array.prototype.slice.call(arguments, 1); var fn = this; return function _fnBind() { var restArgs = Array.prototype.slice.call(arguments); var allArgs = args.concat(restArgs); if (Object.getPrototypeOf(this) === _fnBind.prototype) { var obj = {}; Object.setPrototypeOf(obj, fn.prototype); fn.apply(obj, allArgs); return obj; } else { return fn.apply(ctx, allArgs); } } } /** *Call函数 *@param { String,Number,Object } this指向 @return { String,Number,Object } String,Number,Object *@example fn.myPluginCall('ctx',1,2); */ Function.prototype.myPluginCall = function (ctx) { var args = Array.prototype.slice.call(arguments, 1); ctx = (ctx === undefined || ctx === null ? globalThis : Object(ctx)); var fn = this; var key = Symbol('temp'); Object.defineProperty(ctx, key, { enumerable: false, value: fn }); var list = []; for (var i = 0; i < args.length; i++) { list[i] = 'args[' + i + ']'; } var ret = eval('ctx[key](' + list.join(',') + ')'); delete ctx[key]; return ret; } /** *生成[min,max]范围内的随机整数(大于等于min,小于等于max) *@param { Number } min随机数区间最小值 *@param { Number } max随机数区间最大值 @return { Number } Number随机整数 *@example $.getRandomNumber(1, 3); */ jQuery.getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max + 1 - min) + min); } var _progressNumInfo = 0; var _progressBarIdInfo = "_progressBarBulletbox"; var _timeOutProgress = null; /** *加载进度条显示 *@param { String } barpageload 是否长条进度条 *@param { String } progressBarId 长条进度条对应的id */ jQuery.ajaxDownFakeProgress = function (barpageload, progressBarId) { _progressNumInfo = parseInt(_progressNumInfo) + $.getRandomNumber(1, 5); _progressNumInfo = _progressNumInfo >= 99 ? 99 : _progressNumInfo; barpageload = barpageload || false; progressBarId = progressBarId || _progressBarIdInfo; if (barpageload === true) { $('#' + progressBarId).progressbar('setValue', _progressNumInfo); } else { _changeFileProcess(_progressNumInfo); } if (_progressNumInfo >= 99) { window.clearTimeout(_timeOutProgress); _progressNumInfo = 0; _timeOutProgress = null; return false; } _timeOutProgress = window.setTimeout("$.ajaxDownFakeProgress(" + barpageload + ")", 100); } /** *加载进度条显示 *@param { Number } proNum 进度 *@param { String } barpageload 是否长条进度条 *@param { String } progressBarId 长条进度条对应的id */ jQuery.changeFileBarOrCirProcess = function (proNum, barpageload, progressBarId) { proNum = proNum || 100; barpageload = barpageload || false; progressBarId = progressBarId || _progressBarIdInfo; if (barpageload === true) { $('#' + progressBarId).progressbar('setValue', proNum); } else { _changeFileProcess(proNum); } } /** *下载文件 *@param { Boolean } barpageload 是否长条进度 *@param { Boolean } fakeprogress 是否加进度条 *@param { String } progressBarId 长条进度条对应的id *@param { String } url 下载地址 *@param { String } filename 附件名称 *@param { Object } data 参数 仅支持Object对象 *@param { Function } success 成功后处理事件,非必填 *@example $.ajaxDownFile({ url: 'xxxx', data: { gndm: 'gndm' }, filename: "xx.zip", success: function () { xx(); } }); */ jQuery.ajaxDownFile = function (option) { if (typeof option === 'undefined') throw new Error("Please pass parameters"); if (typeof option.url === 'undefined') throw new Error("Please pass parameters url"); if (typeof option.fakeprogress === 'undefined') { option.fakeprogress = false; } option.barpageload = option.barpageload || false; option.progressBarId = option.progressBarId || _progressBarIdInfo; if (option.barpageload === true) { pageLoadBarDownFile(); } else { pageLoadDownFile(); } if (option.fakeprogress === true) { $.ajaxDownFakeProgress(option.barpageload); } var xhr = new XMLHttpRequest(); xhr.addEventListener('progress', getDownProgressHandler, false); xhr.open('POST', option.url, true); xhr.responseType = "blob"; xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var filename = ''; if (typeof option.filename === 'undefined') { var reqHeader = xhr.getResponseHeader('Content-Disposition'); if (reqHeader) { var reqHeaderFileName = decodeURI(reqHeader); option.filename = reqHeaderFileName.split(';')[1].split('filename=')[1]; } } filename = option.filename; if (typeof window.chrome !== 'undefined') { var a_link = document.createElement('a'); var url = window.URL.createObjectURL(xhr.response); a_link.href = url; a_link.download = filename; a_link.click(); window.URL.revokeObjectURL(url); a_link = null; } else if (typeof window.navigator.msSaveBlob !== 'undefined') { var blob = new Blob([xhr.response], { type: 'application/force-download' }); window.navigator.msSaveBlob(blob, filename); } else { var file = new File([xhr.response], filename, { type: 'application/force-download' }); window.open(URL.createObjectURL(file)); } } else { option.error && option.error(xhr, xhr.statusText); } dispageload(); } } xhr.onerror = function (event) { option.error && option.error(xhr, xhr.statusText, event.message); }; function getDownProgressHandler(event, position, total, percentComplete) { if (event.lengthComputable) { var _proNum = Math.round((event.loaded / event.total) * 100); if (option.fakeprogress === false) { $.changeFileBarOrCirProcess(_proNum, option.barpageload, option.progressBarId); } if (_proNum >= 100) { $.changeFileBarOrCirProcess(_proNum, option.barpageload, option.progressBarId); if (option.fakeprogress === true) { window.clearTimeout(_timeOutProgress); _progressNumInfo = 0; _timeOutProgress = null; } if (typeof option.success === 'function') { option.success(); } } } else { dispageload(); } } var datastr = ''; if (typeof option.data !== 'undefined') { datastr = JSON.stringify(option.data); } xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(datastr); } /** *批量下载文件 *@param { Array } array 待下载数据 *@param { String } data 参数,需包含属性gndm *@param { String } dg datagrid的id *@param { String } zipfileurl 请求压缩文件url *@param { String } downfileurl 请求下载zip文件url *@param { String } delfileurl 请求删除临时文件url *@param { String } zipname 下载文件名称 *@param { String } field 失败显示字段名称 *@example $.ajaxRecursionDownFile({ array: infolist, data: { "gndm": gndm }, datagrid: "dg", zipfileurl: "url1", downfileurl: "url2", delfileurl: "url3", zipname: "附件.zip", field: "xh" }); */ jQuery.ajaxRecursionDownFile = function (option) { if (typeof option === 'undefined') throw new Error("Please pass parameters"); if (typeof option.field === 'undefined' || option.field === null) option.field = "xh"; if (typeof option.array === 'undefined') throw new Error("Please pass parameters array"); if (typeof option.data === 'undefined') throw new Error("Please pass parameters data"); if (option.data.hasOwnProperty('gndm') === false) throw new Error("Please pass parameters data->gndm"); if (typeof option.zipfileurl === 'undefined') throw new Error("Please pass parameters zipfileurl"); if (typeof option.downfileurl === 'undefined') throw new Error("Please pass parameters downfileurl"); if (typeof option.delfileurl === 'undefined') throw new Error("Please pass parameters delfileurl"); pageLoadDown(); var _currentIndex = 0; var _successIndex = 0; var _faileXhInfo = null; var _thisdata = $.deepClone(option.data); function _recursionDownFiles() { if (_currentIndex >= option.array.length) { var msgxx = _faileXhInfo || "无。"; var msg = "压缩成功:" + _successIndex.toString() + "个。失败数据:" + msgxx + "
    点击【确定】按钮下载压缩文件。"; $.messager.alert('提示', msg, 'infoxx', function () { $.ajaxDownFile({ url: option.downfileurl, data: _thisdata, filename: option.zipname, success: function () { var xhr = new XMLHttpRequest(); xhr.open('POST', option.delfileurl, true); xhr.send(); } }); }); $('.panel-tool-close').hide(); if (option.datagrid) { $('#' + option.datagrid).datagrid('clearChecked'); } dispageload(); return false; } var jsonObject = JSON.stringify(option.array[_currentIndex]); var _objdata = option.data; _objdata.json = jsonObject; _objdata.currentIndex = _currentIndex; $.ajax({ type: 'post', url: option.zipfileurl, dataType: "json", data: _objdata, async: true, cache: true, success: function (data) { if (data.zt == "1") { _successIndex++; } else { _faileXhInfo += option.array[_currentIndex][option.field] + ";"; } _currentIndex++; _changeProcess(Math.round((_currentIndex / option.array.length) * 100)); _recursionDownFiles(option.array, option.data.gndm); }, error: function (xhr) { _currentIndex++; _faileXhInfo += option.array[_currentIndex][option.field] + ";"; _changeProcess(Math.round((_currentIndex / option.array.length) * 100)); _recursionDownFiles(option.array, option.data.gndm); } }); } _recursionDownFiles(); }

    你可能感兴趣的:(javascript,前端,html)