把日常後台開發反覆用到的 jQuery 片段整理成一份備忘錄,需要的時候直接抄。
$.ajax({
url: url,
data: parameters,
type: "GET",
dataType: "html",
success: function (html) {
$(renderContainer).attr("title", title);
$(renderContainer).html(html);
$(renderContainer).dialog({
autoOpen: true, width: 590, height: 720,
modal: true, resizable: false, draggable: true
});
}
});
$(".tbl_checked tr[userid='" + idArray[i] + "']").remove();
$("#authorize_reset").live('click', function () {
var idArray = [];
$(":checkbox[id^='userid']").each(function () {
if ($(this).attr("checked") == "checked") {
idArray.push(parseInt($(this).val()));
}
});
});
// 也可以把條件直接寫進選擇器,更精簡
$(":checkbox[id^='userid'][checked]").each(function () {
selectedRoleIdArray.push(parseInt($(this).val()));
});
$(function () {
$(".tbl_checked tr").live('click', function () {
var target = $(this);
if (target.attr("class") == "tr_checked") {
target.removeClass("tr_checked");
} else {
target.addClass("tr_checked");
}
})
});
「2012-12-21」這種格式不能直接相減,要先轉成時間戳:
var compareTime = Date.parse(setTime.replace(/-/g, "/"));
(function ($) {
$.FormatDateTime = function (days) {
var myDate = new Date();
myDate.setDate(myDate.getDate() + days);
var year = myDate.getFullYear();
var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
var day = ("0" + myDate.getDate()).slice(-2);
return year + "-" + month + "-" + day;
}
})(jQuery);
最後還實作了一個可左右搬移內容的雙向清單:點擊列進行選中高亮,再按「添加/刪除」鈕用 insertAfter 把 tr 搬到另一側表格,並在目標表格為空時自動補上表頭。
這份程式碼寫於 jQuery 1.x 時代,.live() 自 1.9 起已移除,請改用 $(document).on('click', selector, handler) 的委派寫法;判斷勾選狀態也建議改用 .prop("checked"),並以 toggleClass("tr_checked") 取代 if/else 的樣式切換。
