IE6 時代遺留問題:<a href="javascript:void(0)"> 點擊無反應,因 void(0) 回傳 undefined 但瀏覽器仍執行預設導向行為。現代開發已不需支援 IE6,但維護舊系統時仍需了解修正方式。
<a href="javascript:void(0);" target="mainFrame" onclick="btnHome_onClick()">首頁</a>
<script>
function btnHome_onClick() {
window.open("com.mcl.common.main.InitHome.flow", "mainFrame");
// 其他邏輯...
}
</script>
javascript:void(0) 是運算式,評估為 undefined,瀏覽器嘗試導向 undefinedjavascript: 協議處理有缺陷,onclick 執行後仍會嘗試導向return false 阻止預設行為<a href="javascript:void(0);" target="mainFrame" onclick="btnHome_onClick(); return false;">首頁</a>
<a href="#" onclick="btnHome_onClick(); return false;">首頁</a>
// 或
<a href="#" onclick="event.preventDefault(); btnHome_onClick();">首頁</a>
<span class="link-like" onclick="btnHome_onClick()">首頁</span>
<style>
.link-like { color: #0066cc; cursor: pointer; text-decoration: underline; }
.link-like:hover { color: #004499; }
</style>
<button type="button" onclick="btnHome_onClick()" class="link-button">首頁</button>
<style>
.link-button { background: none; border: none; color: #0066cc; text-decoration: underline; cursor: pointer; padding: 0; font: inherit; }
</style>
<!-- 真正的連結:有 href、可無障礙、SEO 友善 -->
<a href="/home" target="mainFrame" onclick="return handleNav(this, event)">首頁</a>
<script>
function handleNav(link, event) {
// 中鍵/Command+點擊/Shift+點擊:讓瀏覽器原生處理(新分頁/視窗)
if (event.which === 2 || event.metaKey || event.ctrlKey || event.shiftKey) {
return true;
}
event.preventDefault();
// AJAX 載入或 SPA 路由
loadContent(link.href, 'mainFrame');
return false;
}
</script>
| 寫法 | 鍵盤可聚焦 | 螢幕閱讀器 | SEO | 右鍵選單 |
|---|---|---|---|---|
<a href="..."> | ✅ | ✅ 連結 | ✅ | ✅ 開啟新分頁等 |
<a href="#" onclick="return false"> | ✅ | ✅ 連結 | ❌ | ❌ |
<span onclick> | ❌ (需 tabindex) | ❌ 普通文字 | ❌ | ❌ |
<button> | ✅ | ✅ 按鈕 | ❌ | ❌ |
onclick="...; return false;"href 的 <a>**,配合 event.preventDefault() 控制行為<button>,語意正確且無障礙javascript:void(0)、href="#" 等反模式