表單送出時,我們往往需要把散落在頁面各處的資料——輸入框、清單項目、表格列、資料格——整理成統一的結構。以下這個 providerData 外掛做的就是這件事:依據 DOM 元素的型別,自動組裝成 JSON 字串。
外掛先透過 noConflict() 取得 jQuery 參照,避免與其他函式庫衝突,再以擴充物件的方式掛上 init、getDataName、getData 三個主要方法。其中 getData 會遞迴呼叫自己,處理 div 內的子元素與 table 的每一列。
/// <reference path="jUtil.js" />
$j = jQuery.noConflict();
(function ($j) {
$j.providerData = {
defaultSettings: {
select_Span_Items: false,
select_TD_Items: false,
select_LI_Items: false
},
init: function (options) {
opts = $j.extend({}, $j.providerData.defaultSettings, options);
singleItemJsonFormat = '"{0}":"{1}"';
divItemFormat = '{{0}}';
tableItemFormat = '{0}';
},
// 依序嘗試 dataname 屬性、id、文字內容
getDataName: function (item) {
var dataName = item.attr("dataname");
if (typeof dataName === 'undefined' || dataName == "") dataName = item.attr("Id");
if (typeof dataName === 'undefined' || dataName == "") dataName = item.text();
if (typeof dataName === 'undefined' || dataName == "") dataName = item[0].innerText;
return dataName;
},
getData: function (selector) {
var items;
if (typeof selector !== "object") items = $j(selector);
else items = selector;
var retJsonValue = "";
var subSelector = ":input";
if (opts.select_Span_Items) subSelector += ",span";
if (opts.select_LI_Items) subSelector += ",li";
if (opts.select_TD_Items) subSelector += ",td";
$j.each(items, function (i, item) {
var t = $j(this);
var dataName = $j.providerData.getDataName(t);
// 輸入元件 -> {"name":"value"}
if ($j.util.isInput(t)) {
var itemStr = String.format(singleItemJsonFormat, dataName, t.val());
retJsonValue = retJsonValue + itemStr + ",";
retJsonValue = retJsonValue.trimEnd(",");
}
// div -> 遞迴收集子元素
else if ($j.util.isDiv(t)) {
var subItems = t.find(subSelector);
var subStr = "";
$j.each(subItems, function (i, subItem) {
var tempSubItemStr = $j.providerData.getData("#" + $j(this).attr("id"));
subStr = subStr + "," + tempSubItemStr;
});
subStr = subStr.trimStart(",");
retJsonValue = String.format(divItemFormat, subStr);
}
// table -> 逐列收集,包成陣列
else if ($j.util.isTable(t)) {
var trItems = t.find("TR:gt(0)");
$j.each(trItems, function (i, trItem) {
var subItems = $j(this).find(subSelector);
var subStr = "";
$j.each(subItems, function (i, subItem) {
if ($j.util.isInput($j(this))) {
subStr = subStr + "," + $j.providerData.getData("#" + $j(this).attr("id"));
} else if ($j.util.isTD($j(this)) && $j(this).find(":input").length == 0) {
subStr = subStr + "," + $j.providerData.getData($j(this));
}
});
subStr = subStr.trimStart(",");
retJsonValue = retJsonValue + String.format(divItemFormat, subStr) + ",";
});
retJsonValue = retJsonValue.trimEnd(",");
retJsonValue = "[" + retJsonValue + "]";
}
// li -> {"name":"text"}
else if ($j.util.isLi(t)) {
var itemStr = String.format(singleItemJsonFormat, dataName, t.text());
retJsonValue = retJsonValue + itemStr + ",";
retJsonValue = retJsonValue.trimEnd(",");
}
// td -> 以對應的 th 決定名稱
else if ($j.util.isTD(t)) {
var value = t.text();
var colIndex = t.prevAll().length;
var thItem = t.parent().parent().parent().find("th:eq(" + colIndex + ")");
if (thItem.length == 1) dataName = $j.providerData.getDataName(thItem);
var itemStr = String.format(singleItemJsonFormat, dataName, value);
retJsonValue = retJsonValue + itemStr + ",";
retJsonValue = retJsonValue.trimEnd(",");
}
});
return retJsonValue;
}
};
jProviderData = function (options) {
$j.providerData.init(options);
return $j.providerData.getData(options.selector);
};
})(jQuery);
外掛依賴三個字串擴充方法與一個格式化函式:
String.prototype.trimStart = function (trimStr) {
if (!trimStr) return this;
var temp = this;
while (true) {
if (temp.substr(0, trimStr.length) != trimStr) break;
temp = temp.substr(trimStr.length);
}
return temp;
};
String.prototype.trimEnd = function (trimStr) {
if (!trimStr) return this;
var temp = this;
while (true) {
if (temp.substr(temp.length - trimStr.length, trimStr.length) != trimStr) break;
temp = temp.substr(0, temp.length - trimStr.length);
}
return temp;
};
String.prototype.trim = function (trimStr) {
var temp = trimStr || " ";
return this.trimStart(temp).trimEnd(temp);
};
String.format = function () {
if (arguments.length == 0) return null;
var str = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
str = str.replace(re, arguments[i]);
}
return str;
};
最後一塊拼圖是標籤名稱比對工具,讓外掛知道目前處理的是 table、div、input、span、li 還是 td:
(function ($j) {
$j.util = {
_compareTagName: function (item, tagName) {
return item.attr("tagName").toUpperCase() == tagName.toUpperCase();
},
isTable: function (item) { return $j.util._compareTagName(item, "TABLE"); },
isDiv: function (item) { return $j.util._compareTagName(item, "DIV"); },
isInput: function (item) { return $j.util._compareTagName(item, "INPUT"); },
isSpan: function (item) { return $j.util._compareTagName(item, "SPAN"); },
isLi: function (item) { return $j.util._compareTagName(item, "LI"); },
isTD: function (item) { return $j.util._compareTagName(item, "TD"); }
};
})(jQuery);
整體而言,這個外掛的價值在於把「頁面即資料來源」的取捨寫成了可設定的行為:只要調整 select_Span_Items、select_LI_Items、select_TD_Items 三個開關,就能決定要不要把 span、li、td 一併納入收集範圍。