做原生開發時,總有一些功能是每個專案都要重寫一遍的:按 id 取元素、去空白、算字串顯示長度、格式化字串、Cookie 操作、發個最簡單的 ajax。把這些收在一個物件裡,處處都能少寫幾行。
這裡用的是「立即執行函式回傳物件」的寫法,所有方法都掛在同一個單例上,不需要 new,也沒有原型鏈的負擔:
util = function () {
return {
// 依 id 取元素
$: function (id) {
return document.getElementById(id);
},
// 去除首尾空白
trim: function (str) {
return str.replace(/(^\s+)|(\s+$)/g, "");
},
// 計算顯示長度:全形字元算兩個字寬
len: function (str) {
return str.replace(/[^\x00-\xff]/g, '**').length;
},
// 以 {0} {1} 佔位符格式化字串
format: function (str) {
var arg = arguments;
return str.replace(/\{(\d+)\}/g, function (m, i) {
return arg[parseInt(i) + 1];
});
},
// 同時支援陣列與物件的遍歷,回傳 false 可中斷
each: function (object, callback, args) {
var name, i = 0, length = object.length;
if (args) {
if (length === undefined) {
for (name in object)
if (callback.apply(object[name], args) === false) break;
} else
for (; i < length; )
if (callback.apply(object[i++], args) === false) break;
} else {
if (length === undefined) {
for (name in object)
if (callback.call(object[name], name, object[name]) === false) break;
} else
for (var value = object[0];
i < length && callback.call(value, i, value) !== false; value = object[++i]) {}
}
},
// 寫入 Cookie,hours 為有效小時數
setCookie: function (name, value, hours, path, domain) {
var str = new String();
var nextTime = new Date();
nextTime.setHours(nextTime.getHours() + hours);
str = name + "=" + escape(value);
if (hours) str += ";expires=" + nextTime.toGMTString();
if (path) str += ";path=" + path;
if (domain) str += ";domain=" + domain;
document.cookie = str;
},
// 讀取 Cookie
getCookie: function (name) {
var rs = new RegExp("(^|)" + name + "=([^;]*)(;|$)", "gi").exec(document.cookie), tmp;
if (tmp = rs) return unescape(tmp[2]);
return null;
},
// 刪除 Cookie:把過期時間設到過去
delCookie: function (name) {
document.cookie = name + "=-1" + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
},
/**
* 最精簡的 ajax
* @param config.url 請求位址
* @param config.parms 參數字串
* @param config.method get / post,預設 get
* @param config.success 成功回呼,接收 responseText
*/
ajax: function (config) {
var url = config.url,
parms = (config.parms ? config.parms : "") + "&t=" + new Date().getTime(),
method = config.method || "get",
asy = true,
http_request = null;
if (method.toLowerCase() == "get") {
url = url + "?" + parms;
parms = null;
}
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
throw new Error("不能建立 XMLHttpRequest 物件實例.");
return null;
}
http_request.open(method, url, asy);
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
try {
if (http_request.status == 200) {
config.success(http_request.responseText);
}
} catch (e) {
throw new Error("資料讀取失敗.");
}
}
};
if (method.toLowerCase() == "post") {
http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
http_request.send(parms);
}
};
}();
len 的字寬計算。用 [^\x00-\xff] 把非 ASCII 字元替換成兩個 * 再取長度,是對「中文算兩個字寬」這個需求的快速近似。它對 emoji、CJK 擴充字 etc. 並不精確,但拿來做輸入長度限制的提示綽綽有餘。
format 的佔位符。util.format("{0} 有 {1} 筆", a, b) 這種寫法比字串相加可讀得多,也少了漏空格、漏加號的機會。
each 的兩種簽名。帶第三個參數時走 apply 版本,不帶時走 call 版本並把索引當第一個參數傳入。callback 回傳 false 即可中斷,這和 jQuery 的 $.each 慣例一致。
ajax 裡的時間戳。GET 請求的字串上永遠掛一個 &t=時間戳,用來避免瀏覽器快取;代價是 GET 請求無法被快取,如果這不是你想要的行為,記得拿掉。
作為一份「看懂自己每行在幹嘛」的工具類,它仍然有參考價值,尤其是 each、format、trim 這幾個與框架無關的純函式。
但 ajax 這一段已經不建議再用:它沒有錯誤回呼、沒有逾時控制、無法處理非同步以外的情境,也沒有回應標頭的存取。新專案請直接用 fetch 或 XMLHttpRequest 加上 Promise 封裝。Cookie 那三個方法也建議改用 document.cookie 的現代封装,並注意 escape/unescape 已被標記為不建議使用,改用 encodeURIComponent 會更安全。