做網頁的朋友想必都遇過多層級選單的情境:點擊某個選單按鈕時,若其子選單正顯示著就將它隱藏,若隱藏著就將它展開。傳統的 JavaScript 做法得先用 getElementById 取出子選單容器的 id,再判斷該容器的 display 樣式——等於 block 就設為 none,不等於就設為 block。
如果想讓效果更精緻,例如點擊時不是「啪」地瞬間隱藏或顯示,而是高度平滑地過渡,那就得靠 setTimeout 反覆調整子選單的 height;要是連透明度也要平滑淡入淡出,需要撰寫的程式碼更是可觀。對 JavaScript 基礎不紮實的人來說,恐怕只能拿別人寫好的程式碼來改了。
然而用 jQuery 實現上述所有效果,只需要一句話:$("#a").toggle("slow")。學會 jQuery 之後,你還需要抄襲修改別人的程式碼嗎?下面我們逐一認識 jQuery 用於效果處理的方法。
偉大的 jQuery 讓寫 JavaScript 變得高效,它對 Ajax 的封裝也相當到位。不過使用一段時間後你會發現,jQuery 在處理 JSON 字串方面的功能並不算強,至少比起 prototype.js 有一段差距。
過去習慣了 prototype.js 的 JSON 資料處理方式,進行 Ajax 開發時十分便利;而 jQuery 僅提供了一個簡單的 jQuery.getJSON() 方法,本身並未提供對 JSON 資料的轉換處理。把 JSON 字串轉為 JavaScript 物件還容易,用 eval() 即可;但要把 JavaScript 資料型別反過來轉成 JSON 字串就頗為棘手,於是很多人剛開始不得不同時載入 prototype.js 與 jQuery。
以下程式碼為 jQuery 補上了完整的 JSON 轉換能力:
// 擴充 jQuery 對 JSON 字串的轉換
jQuery.extend({
/** 將 json 字串轉換為物件
* @param json 字串
* @return 回傳 object, array, string 等物件 */
evalJSON: function (strJson) {
return eval("(" + strJson + ")");
}
});
jQuery.extend({
/** 將 Javascript 資料型別轉換為 json 字串
* @param 待轉換物件,支援 object, array, string, function, number, boolean, regexp
* @return 回傳 json 字串 */
toJSON: function (object) {
var type = typeof object;
if ('object' == type) {
if (Array == object.constructor) type = 'array';
else if (RegExp == object.constructor) type = 'regexp';
else type = 'object';
}
switch (type) {
case 'undefined':
case 'unknown':
return;
break;
case 'function':
case 'boolean':
case 'regexp':
return object.toString();
break;
case 'number':
return isFinite(object) ? object.toString() : 'null';
break;
case 'string':
return '"' + object.replace(/(\\|")/g, "\\$1")
.replace(/\n|\r|\t/g, function () {
var a = arguments[0];
return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : "";
}) + '"';
break;
case 'object':
if (object === null) return 'null';
var results = [];
for (var property in object) {
var value = jQuery.toJSON(object[property]);
if (value !== undefined) results.push(jQuery.toJSON(property) + ':' + value);
}
return '{' + results.join(',') + '}';
break;
case 'array':
var results = [];
for (var i = 0; i < object.length; i++) {
var value = jQuery.toJSON(object[i]);
if (value !== undefined) results.push(value);
}
return '[' + results.join(',') + ']';
break;
}
}
});
var obj = {
name: "sean",
friends: ["fans", "bruce", "wawa"],
action: function () {
alert("gogogog");
},
boy: true,
age: 26,
reg: /\b([a-z]+) \1\b/gi,
child: {
name: "none",
age: -1
}
};
var json = $.toJSON(obj); // 物件轉為 JSON 字串
var objx = $.evalJSON(json); // JSON 字串轉回物件
透過這兩個擴充方法,jQuery 便能像 prototype.js 一樣輕鬆地在物件與 JSON 字串之間雙向轉換,讓 Ajax 開發更加順手。