下面 These 這幾段都是日常開發中反覆用到的小工具,直接複製改一改就能上場。
function getUrlPara(paraName) {
var sUrl = location.href;
var sReg = "(?://?|&){1}" + paraName + "=([^&]*)";
var re = new RegExp(sReg, "gi");
re.exec(sUrl);
return RegExp.$1;
}
用正則從 location.href 中擷取指定參數的值。現代專案更推薦直接用 new URLSearchParams(location.search).get(paraName),程式碼短得多也不必處理編碼。
var pn = $("#gotopagenum").val();
location.href = "NewList.aspx?pagenum=" + pn;
透過 location.href 完成客戶端導航,這裡示範帶頁碼跳轉。
function Convert(money) {
var s = money + "";
if (s.indexOf(".") == -1) s += ".00"; // 沒有小數點就補 .00
if (/\.\d$/.test(s)) s += "0"; // 只有一位小數補 0
while (/\d{4}(\.|,)/.test(s)) { // 每三位插入逗號
s = s.replace(/(\d)(\d{3}(\.|,))/, "$1,$2");
}
return s;
}
金額顯示時常用。Intl.NumberFormat 已經內建這個能力,新專案可以直接用。
function IsNumeric(txt) {
if (txt == "") return false;
if (txt.indexOf(",") > 0) txt = txt.replace(",", "");
return !isNaN(txt);
}
function changeTwoDecimal_f(x) {
var f_x = parseFloat(x);
if (isNaN(f_x)) {
alert('function:changeTwoDecimal->parameter error');
return false;
}
f_x = Math.round(f_x * 100) / 100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2) s_x += '0';
return s_x;
}
數字運算時搭配 parseFloat 與 parseInt 使用。若要避免浮點誤差,金額計算建議以「分」為單位做整數運算。
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
$("#txtDate1").val(year + "-" + month + "-01");
$("#txtDate2").val(year + "-" + month + "-" + day);
常用來帶入查詢條件的起訖日。注意這裡用 getFullYear() 而不是 getYear(),後者已不建議使用。
function NowTimeCode() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minutes = now.getMinutes();
var second = now.getSeconds();
var millisecond = now.getMilliseconds();
var pad = function(n, len) {
n = String(n);
while (n.length < len) n = "0" + n;
return n;
};
return year + pad(month, 2) + pad(day, 2) + pad(hour, 2)
+ pad(minutes, 2) + pad(second, 2) + pad(millisecond, 3);
}
把年月日時分秒毫秒拼成定長字串,可以在某些場景下代替 GUID 當唯一識別碼。這裡我把原本層層 if 的補零邏輯抽成 pad 函式,可讀性會好很多。