網站常用的一些javascript封裝 簡化調用

//用於網頁地址參數
//參數中包含出瞭英文中文數字之外的其他符號時進行編碼並在前面加“==”進行標識,否則直接返回
//解碼時根據是否含有“==”標識來決定是否要解碼
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64Encode = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

function Base64Encode(str) {
    var reg=/^[a-zA-Z0-9]*$/;
    if(str==null || reg.test(str))
    {
        return str;
    }
    str=Utf16To8(str);
    var out, i, len;
    var c1, c2, c3;
    
    len = str.length;
    i = 0;
    out = "";
    while(i > 2);
        out += base64EncodeChars.charAt((c1 & 0x3) <> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3)<> 4));
        out += base64EncodeChars.charAt((c2 & 0xf) <> 2);
    out += base64EncodeChars.charAt(((c1 & 0x3)<> 4));
    out += base64EncodeChars.charAt(((c2 & 0xf) <>6));
    out += base64EncodeChars.charAt(c3 & 0x3f);
    }

    out=out.replace(/\//g,"@@")
    return "==" + out;
}
function Utf16To8(str) {
    var out, i, len, c;

    out = "";
    len = str.length;
    for (i = 0; i = 0x0001) && (c  0x07ff) {
            out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        } else {
            out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        }
    }
    return out;
}

function Utf8To16(str) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = str.length;
    i = 0;
    while (i > 4) {
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                // 0xxxxxxx
                out += str.charAt(i - 1);
                break;
            case 12: case 13:
                // 110x xxxx   10xx xxxx
                char2 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
                break;
            case 14:
                // 1110 xxxx  10xx xxxx  10xx xxxx
                char2 = str.charCodeAt(i++);
                char3 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x0f) << 12) |
                       ((char2 & 0x3f) << 6) |
                       ((char3 & 0x3f) << 0));
                break;
        }
    }

    return out;
}
//base64編碼結束

function ValidateEmail(str) {
    var r = /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (r.test(str)) {
        return true;
    } else {
        return false;
    }
}

function ValidateTelPhone(str) {
    var s = /^(\d{2,4})(-(\d{7,8}))$/;
    if (s.test(str)) {
        return true;
    } else {
        return false;
    }
}

function ValidatePhone(str) {
    var regu = /^[1][3,5,8][0-9]{9}$/;
    var re = new RegExp(regu);
    if (re.test(str)) {
        return true;
    }
    else {
        return false;
    }
}


/*設置與獲取Cookie*/
var Cookie = {}
Cookie.write = function (key, value, duration) {
    var d = new Date();
    d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 30);
    document.cookie = key + "=" + encodeURI(value) + "; expires=" + d.toGMTString();
};
Cookie.read = function (key) {
    var arr = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
    if (arr != null)
        return decodeURIComponent(arr[2]);
    return "";
};

//input去掉默認內容還原編輯樣式
function g_on_setvalue(id, value, cname) {
    var obj = document.getElementById(id);
    if (obj.value != value) {
        return false;
    }
    obj.value = "";
    obj.className = cname;
}


//將日期轉換成"yyyy-mm-dd"格式 第二個參數為返回類型傳入'ym':yyyy-mm,'md':mm-dd,默認為'yyyy-mm-dd'
function ConvertDateFormat(strDate, sye) {
    if (strDate == null || strDate == "" || strDate == "0") {
        return ("");
    }
    else {
        try {
            var ExDate = new Date(strDate.replace(/-/g, "/"));
            var yyyy = ExDate.getFullYear();
            var mm = ExDate.getMonth() + 1; mm = mm < 10 ? "0" + mm : mm;
            var dd = ExDate.getDate(); dd = dd < 10 ? "0" + dd : dd;
            switch (sye) {
                case "ym":
                    return yyyy + "-" + mm;
                    break;
                case "md":
                    return mm + "-" + dd;
                    break;
                default:
                    return yyyy + "-" + mm + "-" + dd;
                    break;
            }
        }
        catch (e) {
            return ("")
        }
    }
}
//將日期轉換成"yyyymmdd"格式 第二個參數為返回類型傳入'ym':yyyy-mm,'md':mm-dd,默認為'yyyy-mm-dd'
function ConvertDateFormatString(strDate, sye) {
    if (strDate == null || strDate == "" || strDate == "0" || strDate.length < 8) {
        return ("");
    }
    else {
        try {
            var ExDate = new Date(strDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1/$2/$3"));
            var yyyy = ExDate.getFullYear();
            var mm = ExDate.getMonth() + 1; mm = mm < 10 ? "0" + mm : mm;
            var dd = ExDate.getDate(); dd = dd < 10 ? "0" + dd : dd;
            switch (sye) {
                case "ym":
                    return yyyy + "-" + mm;
                    break;
                case "md":
                    return mm + "-" + dd;
                    break;
                default:
                    return yyyy + "-" + mm + "-" + dd;
                    break;
            }
        }
        catch (e) {
            return ("")
        }
    }
}
//獲取URL中的request參數
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
    { return decodeURIComponent(r[2]); }
    else
    { return ""; }

}
function aUrl(url) {
    window.location.href = url;
}
function rForm(formid) {
    document.getElementById(formid).reset();
}
//全選
function checkAll(id, checkname) {
    var obj = document.getElementById(id);
    if (obj.checked) {
        $("input[name='" + checkname + "']").attr('checked', true)
    } else {
        $("input[name='" + checkname + "']").attr('checked', false)
    }
}
//取checkbox 返回數組
function checkvalue(name) {
    var obj = document.getElementsByName(name);
    var aList = [];
    var j = 0;
    for (var i = 1; i  nMaxLen) {
        o.value = o.value.substring(0, nMaxLen)
    }
}
//驗證整數
function intcheck(thisobject) {
    if ($(thisobject).val().toString() == "") { return; }
    if ($(thisobject).val().toString() == "0") { return; }
    var number = $(thisobject).val();
    var type = "^[0-9]*[1-9][0-9]*$";
    var re = new RegExp(type);
    if (number.match(re) == null) {
        alert("請輸入大於零的整數!");
        $(thisobject).val("");
        return;
    }

}
//比較時間
function comTime(begintime, endtime) {
    var arr = begintime.split("-");
    var starttime = new Date(arr[0], arr[1], arr[2]);
    var starttimes = starttime.getTime();

    var arrs = endtime.split("-");
    var lktime = new Date(arrs[0], arrs[1], arrs[2]);
    var lktimes = lktime.getTime();

    if (starttimes >= lktimes) {
        return false;
    }
    else
        return true;
}
//open window
function showMyModalDialog(url, width, height,Title) {
    var now = new Date();
    var urlr
    if (url.indexOf('=') == -1) {
        urlr = url + "?cach=" + escape(now);
    }
    else {
        urlr = url + "&cach=" + escape(now);
    }
    if (Title !=null)
    {
        JqueryDialog.Open(Title, urlr, width, height);
    }
    else
    {
        JqueryDialog.Open('', urlr, width, height);
    }

    
}

//open mini window
function openwindow(url, height, width) {
    var t = (window.screen.availHeight - 400) / 2;
    var l = (window.screen.availWidth - 600) / 2;
    window.open(url, "Query", "height=" + height + ", width=" + width + ", top=" + t + ",left=" + l + ",toolbar=no, menubar=no, scrollbars=yes, resizable=no");
}  

//confirm 
function Confirm(msg, control) {
    $.messager.confirm('確認', msg, function (r) {
        if (r) {
            eval(control.toString().slice(11));
        }
    });
    return false;
} 

//gridview
function gridview(objgridview) {
    //get obj id
    var gridviewId = "#" + objgridview;
    //even
    $(gridviewId + ">tbody tr:even").addClass("NormalColor");
    //first
    $(gridviewId + ">tbody tr:first").removeClass("NormalColor").addClass("HeadColor");
    //odd
    $(gridviewId + ">tbody tr:odd").addClass("AlterColor");
    //move and click edit by hb 20130206
    $(gridviewId + ">tbody tr").hover(function () {
        $(this).addClass("HoverColor");
    }, function () {
        $(this).removeClass("HoverColor");
    }).click(function () {
        var $check = $(this).find("input:checkbox");
        if ($check.attr("checked")) {
            $(this).addClass("SelectColor");
        }
        else {
            $(this).removeClass("SelectColor");
        }
    });
    //all check
    $("#chkAll").click(function () {
        $(gridviewId + '>tbody >tr >td >input:checkbox:visible').attr('checked', this.checked);
    });
    //check status
    $(gridviewId + ' >tbody >tr >td >input:checkbox').click(function () {
        var expr1 = gridviewId + ' >tbody >tr >td >input:checkbox:checked';
        var expr2 = gridviewId + ' >tbody >tr >td >input:checkbox';
        var selectAll = $(expr1).length == $(expr2).length;
        $('#chkAll').attr('checked', selectAll);
    });
}

//load
function Load() {
    $("

").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 }); } //display Load function dispalyLoad() { $(".datagrid-mask").remove(); $(".datagrid-mask-msg").remove(); } function checkroleinfo(checkresult, checkaction) { if (checkresult == "1") { } else { $("[rolecheck='" + checkaction + "']").remove(); } } function showLoad(tipInfo) { var eTip = document.createElement('p'); eTip.setAttribute('id', 'tipDiv'); eTip.style.position = 'absolute'; eTip.style.display = 'none'; eTip.style.border = 'solid 0px #D1D1D1'; eTip.style.backgroundColor = '#4B981D'; eTip.style.padding = '5px 15px'; eTip.style.top = '10px'; eTip.style.right = '10px'; eTip.style.width = '120px'; eTip.innerHTML = '  ' + tipInfo + ''; try { document.body.appendChild(eTip); } catch (e) { } $("#tipDiv").css("float", "right"); $("#tipDiv").css("z-index", "99"); $('#tipDiv').fadeIn(); } function closeLoad() { $('#tipDiv').fadeOut(); } function ForDight(Dight, How) { Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How); return Dight; } function changetitle(object) { $(object).attr("title", $(object).val()); } function atoc(numberValue) { var numberValue = new String(Math.round(numberValue * 100)); // 數字金額 var chineseValue = ""; // 轉換後的漢字金額 var String1 = "零壹貳叁肆伍陸柒捌玖"; // 漢字數字 var String2 = "萬仟佰拾億仟佰拾萬仟佰拾元角分"; // 對應單位 var len = numberValue.length; // numberValue 的字符串長度 var Ch1; // 數字的漢語讀法 var Ch2; // 數字位的漢字讀法 var nZero = 0; // 用來計算連續的零值的個數 var String3; // 指定位置的數值 if (len > 15) { alert("超出計算范圍"); return ""; } if (numberValue == 0) { chineseValue = "零元整"; return chineseValue; } String2 = String2.substr(String2.length - len, len); // 取出對應位數的STRING2的值 for (var i = 0; i = 3) { Ch1 = ""; Ch2 = ""; nZero = nZero + 1; } else { Ch1 = ""; Ch2 = String2.substr(i, 1); nZero = nZero + 1; } if (i == (len - 11) || i == (len - 3)) { // 如果該位是億位或元位,則必須寫上 Ch2 = String2.substr(i, 1); } } chineseValue = chineseValue + Ch1 + Ch2; } if (String3 == 0) { // 最後一位(分)為0時,加上“整” chineseValue = chineseValue + "整"; } return chineseValue; } var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; function generateMixed(n) { var res = ""; for (var i = 0; i < n; i++) { var id = Math.ceil(Math.random() * 35); res += chars[id]; } return res; } /// /// 實現數據的四舍五入法 /// /// 要進行處理的數據 /// 保留的小數位數 /// 四舍五入後的結果 function Round(v, x) { var isNegative = false; //如果是負數 if (v < 0) { isNegative = true; v = -v; } var IValue = 1; for (var i = 1; i <= x; i++) { IValue = IValue * 10; } var Int = Math.round(v * IValue, 0); v = Int / IValue; if (isNegative) { v = -v; } return v; } /// /// 實現數據的向上取整 /// /// 要進行處理的數據 /// 保留的小數位數 /// 向上取整後的結果 function Ceiling(v, x) { var isNegative = false; //如果是負數 if (v < 0) { isNegative = true; v = -v; } var IValue = 1; for (var i = 1; i <= x; i++) { IValue = IValue * 10; } var Int = Math.ceil(v * IValue); v = Int / IValue; if (isNegative) { v = -v; } return v; } /// /// 實現數據的向下取整 /// /// 要進行處理的數據 /// 保留的小數位數 /// 向下取整後的結果 function Floor(v, x) { var isNegative = false; //如果是負數 if (v < 0) { isNegative = true; v = -v; } var IValue = 1; for (var i = 1; i <= x; i++) { IValue = IValue * 10; } var Int = Math.floor(v * IValue); v = Int / IValue; if (isNegative) { v = -v; } return v; } /// /// 實現數據的四舍五入,向上取整,向下取整 /// /// 要進行處理的數據 /// 保留的小數位數 /// 1四舍五入,2向上取整,3向下取整 /// function DecimalProcessing(v, x, type) { var result = 0; switch (type) { case "1": result = Round(v, x); break; case "2": result = Ceiling(v, x); break; case "3": result = Floor(v, x); break; default: result = Round(v, x); break; } return result; } //除法函數,用來得到精確的除法結果 // 說明:javascript的除法結果會有誤差,在兩個浮點數相除的時候會比較明顯。這個函數返回較為精確的除法結果。 //調用:accDiv(arg1,arg2) //返回值:arg1除以arg2的精確結果 function accDiv(arg1, arg2) { var t1 = 0, t2 = 0, r1, r2; try { t1 = arg1.toString().split(".")[1].length } catch (e) { } try { t2 = arg2.toString().split(".")[1].length } catch (e) { } with (Math) { r1 = Number(arg1.toString().replace(".", "")) r2 = Number(arg2.toString().replace(".", "")) return (r1 / r2) * pow(10, t2 - t1); } } //給Number類型增加一個p方法,調用起來更加方便。 Number.prototype.p = function (arg) { return accDiv(this, arg); } //乘法函數,用來得到精確的乘法結果 //說明:javascript的乘法結果會有誤差,在兩個浮點數相乘的時候會比較明顯。這個函數返回較為精確的乘法結果。 //調用:accMul(arg1,arg2) //返回值:arg1乘以 arg2的精確結果 function accMul(arg1, arg2) { var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length } catch (e) { } try { m += s2.split(".")[1].length } catch (e) { } return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m) } // 給Number類型增加一個mul方法,調用起來更加方便。 Number.prototype.mul = function (arg) { return accMul(arg, this); } //加法函數,用來得到精確的加法結果 //說明:javascript的加法結果會有誤差,在兩個浮點數相加的時候會比較明顯。這個函數返回較為精確的加法結果。 //調用:accAdd(arg1,arg2) // 返回值:arg1加上arg2的精確結果 function accAdd(arg1, arg2) { var r1, r2, m, c; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } c = Math.abs(r1 - r2); m = Math.pow(10, Math.max(r1, r2)) if (c > 0) { var cm = Math.pow(10, c); if (r1 > r2) { arg1 = Number(arg1.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", "")) * cm; } else { arg1 = Number(arg1.toString().replace(".", "")) * cm; arg2 = Number(arg2.toString().replace(".", "")); } } else { arg1 = Number(arg1.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", "")); } return (arg1 + arg2) / m } //給Number類型增加一個add方法,調用起來更加方便。 Number.prototype.add = function (arg) { return accAdd(arg, this); } //減法函數,用來得到精確的減法結果 //說明:javascript的減法結果會有誤差,在兩個浮點數相減的時候會比較明顯。這個函數返回較為精確的減法結果。 //調用:accSub(arg1,arg2) // 返回值:arg1加上arg2的精確結果 function accSub(arg1, arg2) { var r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //動態控制精度長度 n = (r1 >= r2) ? r1 : r2; return ((arg1 * m - arg2 * m) / m).toFixed(n); }

發佈留言