萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML Input 按鈕導航大全:頁面跳轉、新窗口、返回、確認彈窗一網打盡

基礎導航模式

需求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 支持
copyright © 萬盛學電腦網 all rights reserved