基礎導航模式
| 需求 | HTML 代碼 | 說明 |
| 當前頁跳轉 |
<input type="button" value="確定" onclick="location.href='page.html'"> |
同源導航,保留歷史記錄 |
| 返回上一頁 |
<input type="button" value="返回" onclick="history.back()"> |
等同瀏覽器後退按鈕,history.go(-1) 同理 |
| 新窗口打開 |
<input type="button" value="新窗口" onclick="window.open('page.html')"> |
默認瀏覽器標籤頁/彈窗取決於用戶設置 |
| 指定尺寸無邊框窗口 |
<input type="button" value="彈窗" onclick="window.open('page.html','','width=800,height=600,resizable=yes,scrollbars=yes')"> |
特性字符串控制窗口特性,現代瀏覽器部分限制生效 |
組合導航模式
新窗口 + 當前頁跳轉
onclick="window.open('page1.html'); location.href='page2.html';"
彈窗確認後跳轉
onclick="alert('確認提交?'); location.href='submit.html'; return false;"
onclick="if(confirm('確認提交?')) location.href='submit.html'; return false;"
現代最佳實踐:語義化 Button + 事件綁定
HTML
JavaScript (委託綁定)
document.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-action], button[data-url]');
if (!btn) return;
e.preventDefault();
// 確認對話框
if (btn.dataset.confirm && !confirm(btn.dataset.confirm)) return;
const url = btn.dataset.url;
const action = btn.dataset.action;
if (action === 'back') {
history.back();
} else if (btn.dataset.popup) {
const opts = JSON.parse(btn.dataset.popup);
const features = Object.entries(opts).map(([k,v])=>`${k}=${v}`).join(',');
window.open(url, '_blank', features);
} else if (url) {
location.href = url;
}
});
安全性與 UX 建議
- 避免在
onclick 內聯大段 JS,採用 data-* 屬性 + 委託綁定
- 跨域
window.open 返回 null,無法操作新窗口 (同源策略)
- 移動端
window.open 可能被攔截,優先使用 location.href 或 target="_blank" 鏈接
- 表單提交按鈕使用
type="submit" 配合 form 屬性,無需 JS
- 無障礙:按鈕需有清晰文本,圖標按鈕添加
aria-label
總結對比
| 方式 | 適用場景 | 優點 | 缺點 |
| location.href | 同源頁面跳轉 | 簡單、語義清晰 | 當前頁離開 |
| window.open | 新窗口/彈窗 | 保留原頁面 | 可能被攔截、跨域受限 |
| history.back/go | 返回導航 | 無需知道具體 URL | 依賴歷史棧 |
| <a href> | 導航鏈接 | SEO友好、無障礙、可預加載 | 樣式需重置 |
| <button> + JS | 複雜交互 | 語義正確、可攜帶數據屬性 | 需 JS 支持 |