表單是 Web 互動的核心。本文彙整 12 類常見表單操作場景,提供原生 JS 與 jQuery 兩種寫法,並標註現代最佳實踐與避坑指南。
// 當前頁面
window.location.reload();
// 父視窗 (window.open 開啟的子視窗)
window.opener.location.reload();
// 父視窗 (showModalDialog 開啟的模態視窗)
window.dialogArguments.location.reload();
function openCentered(url, w=600, h=400) {
var left = (screen.width - w) / 2;
var top = (screen.height - h) / 2;
return window.open(url, '_blank',
`width=${w},height=${h},left=${left},top=${top},resizable=yes,scrollbars=yes`);
}
function openModal(url, w=600, h=400) {
var left = (screen.width - w) / 2;
var top = (screen.height - h) / 2;
return window.showModalDialog(url, window,
`dialogWidth:${w}px; dialogHeight:${h}px; dialogLeft:${left}px; dialogTop:${top}px; resizable:no; status:no`);
}
<!-- JSP/ASP.NET 伺服端 -->
<% response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
response.setHeader("Pragma", "no-cache"); // HTTP 1.0
response.setDateHeader("Expires", 0); // Proxies %>
<!-- HTML Meta (輔助,不保證) -->
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
function closeWindowSilently() {
// 現代瀏覽器:只能關閉由 script 開啟的視窗
if (window.opener) {
window.opener = null; // 斷開關係
window.close();
} else {
// 非 script 開啟的視窗無法靜默關閉,會詢問使用者
window.close();
}
}
var closeTimer = setTimeout(function() {
window.close();
}, 100000); // 100秒
// 若需取消
clearTimeout(closeTimer);
// 父視窗
function openModify(id) {
window.showModalDialog(`modify.html?id=${id}`, window, 'dialogWidth:400px;dialogHeight:300px;resizable:no');
// 子視窗關閉後自動重載
location.reload();
}
// 子視窗 (modify.html)
var id = new URLSearchParams(location.search).get('id');
// ... 處理邏輯 ...
window.returnValue = { success: true, id: id };
window.close();
// 原生 JS (推薦)
document.getElementById('elemId').style.display = 'none'; // 隱藏
document.getElementById('elemId').style.display = ''; // 顯示 (恢復預設)
// jQuery
$('#elemId').hide();
$('#elemId').show();
// 或切換
$('#elemId').toggle();
// 原生
document.getElementById('btnSubmit').disabled = true; // 停用
document.getElementById('btnSubmit').disabled = false; // 啟用
// 切換狀態 (實用範例)
var input = document.getElementById('myInput');
var btn = document.getElementById('toggleBtn');
btn.onclick = function() {
input.disabled = !input.disabled;
input.value = input.disabled ? '已停用' : '可編輯';
this.value = input.disabled ? '啟用' : '停用';
};
function submitForm(actionUrl) {
var form = document.forms['myForm'] || document.getElementById('myForm');
if (form) {
form.action = actionUrl;
form.submit();
}
}
// 現代 fetch 替代 (非同步,不跳轉)
async function submitAjax(formId, url) {
var form = document.getElementById(formId);
var formData = new FormData(form);
var res = await fetch(url, { method: 'POST', body: formData });
return res.json();
}
// 原生
function getRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) return radios[i].value;
}
return null;
}
// jQuery (極簡)
var val = $('input[name="workMode"]:checked').val();
// 原生
var select = document.getElementById('province');
select.options.add(new Option('請選擇', '')); // 預設項
data.forEach(function(item) {
select.options.add(new Option(item.name, item.id));
});
// 清空並重建
select.innerHTML = '';
select.options.add(new Option('請選擇', ''));
// ... 新增項目 ...
// jQuery
$('#province').empty().append('');
$.each(data, function(i, item) {
$('#province').append($('
<script src="/js/prototype-1.6.js"></script>
<script>
function editIpSegment() {
var url = '/api/ipsegment/changeNotice';
var params = { startip: startip, endip: endip, lindex: lindex };
new Ajax.Request(url, {
method: 'get',
parameters: params,
asynchronous: false, // 同步 (不建議,會阻塞 UI)
onComplete: function(response) {
var result = response.responseText;
// 處理結果
}
});
}
</script>
| 舊寫法 | 現代替代 | 優勢 |
|---|---|---|
| window.showModalDialog | 自訂 Modal + Promise | 跨瀏覽器、無障礙、響應式 |
| Prototype.js AJAX | fetch / axios | 標準、Promise、體積小 |
| document.all / attachEvent | document.getElementById / addEventListener | 標準、效能佳 |
| 同步 AJAX (async: false) | async/await + Promise | 不阻塞主執行緒、錯誤處理完善 |
| innerHTML 拼接 HTML | template 元素 / 框架 (Vue/React) | XSS 防護、維護性高 |
表單操作看似基礎,實則牽涉事件模型、DOM 操作、非同步流程、安全性等核心能力。掌握原生 API 並善用現代工具鏈,才能寫出健壯、可維護的程式碼。