本文整理自實戰項目中的高頻工具代碼片段,涵蓋前端(JavaScript/jQuery)與後端(Java)常見場景,供快速查閱與復制適配。
// 視口高度/寬度
$(window).height(); $(window).width();
// 元素尺寸
$("#chartbottomdiv").width(); // 必須用 .width() 而非 .css("width")
// 保留 N 位小數
function toFixedN(value, n) {
if (value == null || value === "" || value === undefined) return value;
return Number(value).toFixed(n);
}
// 保留 3 位有效數字(科學計數法輔助)
function threeEffective(value) {
if (value == null || value === "" || value === undefined) return value;
return value < 1000 ? Number(value).toPrecision(3) : Number(value).toFixed(0);
}
// 一維數組
$.each(["one","two"], function(){ console.log(this); }); // this 為元素值
// 二維數組
$.each([[1,4],[4,6]], function(i, item){ console.log(item[0]); }); // item 為子數組
// 對象遍歷
$.each({one:1, two:2}, function(key, val){ console.log(key, val); });
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
return r ? decodeURI(r[2]) : null;
}
function formatMMDD(str) {
return str.substring(0,2).replace(/^0/,'') + "月" + str.substring(2,4).replace(/^0/,'') + "日";
}
window.onresize = function() {
clearTimeout(window.resizeTimer);
window.resizeTimer = setTimeout(setContainerSize, 200);
};
// jQuery 1.7+ 推薦 on()
$("#parent").on("click", ".child", function(){ ... });
// 多事件綁定
$("#parent").on({
click: handler1,
dblclick: handler2,
mouseleave: handler3
}, ".child");
$('#overStation').dblclick(function(){
$('#overStation option:selected').remove();
}).mousedown(function(e){
if (e.which === 3) $(this).children("option:selected").remove();
}).bind("contextmenu", function(){ return false; }); // 禁用右鍵菜單
success: function(data) {
var json = eval("(" + data + ")"); // 或 JSON.parse(data)
$.each(json, function(index, item){
var name = item.groupname; // 訪問屬性
});
}
// 原生 DOM
var sel = document.getElementById('overStation');
while (sel.options.length) sel.removeChild(sel.options[0]);
// jQuery
$("#group").html(""); // 或 $("#group").empty()
$.messager.alert({
title: '提示', msg: '操作成功',
fn: function(){ window.location.reload(); }
});
Math.round(value); // 返回 Number
public String parseTags(String html) {
html = html.replaceAll("(?is)", "");
html = html.replaceAll("(?is)", "");
html = html.replaceAll("(?s)<[^>]*>", ""); // 移除所有標簽
html = html.replaceAll(" ", " ")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("&", "&")
.replaceAll(""", "\"");
return html.trim();
}
| 版本 | 方法 | 語法 | 備註 |
|---|---|---|---|
| <1.9 | .delegate() | $(parent).delegate(child, event, fn) | 已棄用 |
| ≥1.7 | .on() | $(parent).on(event, child, fn) | 統一 API,支持動態元素 |
核心差異:on() 參數順序為 event, selector, data, handler,delegate() 為 selector, event, data, handler。
(原文多為前端,此處補充常用 Java 工具)
// 自動拆裝箱 (JDK 1.5+) Integer i = 100; // 裝箱 Integer.valueOf(100) int n = new Integer(100); // 拆箱 integer.intValue()
Listunique = list.stream().distinct().collect(Collectors.toList()); Map idMap = users.stream().collect(Collectors.toMap(User::getId, u -> u));
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
工具方法的核心價值在於統一異常處理、屏蔽瀏覽器差異、提升語義可讀性。建議項目中建立 utils.js / CommonUtils.java 統一維護,避免分散複製導致版本不一致。