在前端開發中,常需根據登錄狀態、權限等條件決定鏈接跳轉目標。本文演示如何用 jQuery 綁定點擊事件、判斷頁面元素狀態、動態設置 `window.location.href` 實現條件導航,並解析 `` 與 `onclick` 的配合模式。
<a href="javascript:void(0)" onclick="checkValidate()">水覓微博</a>
<span id="signOut" style="display:none">用戶名</span> <!-- 登錄後顯示 -->
function checkValidate() {
if ($('#signOut').text().trim()) { // 有文本內容視為已登錄
window.location.href = '<%=basePath%>/jsp/weibo/index.jsp';
} else {
window.location.href = '<%=basePath%>index.jsp'; // 未登錄跳轉首頁/登錄頁
}
}
<a id="weiboLink" href="<%=basePath%>index.jsp">水覓微博</a>
<script>
$(function() {
$('#weiboLink').on('click', function(e) {
e.preventDefault(); // 阻止默認跳轉
var target = $('#signOut').text().trim()
? '<%=basePath%>/jsp/weibo/index.jsp'
: this.href; // 回退到原始 href
window.location.href = target;
});
});
</script>
$('#weiboLink').on('click', function(e) {
e.preventDefault();
var $link = $(this);
$.get('/api/check-login').done(function(res) {
if (res.loggedIn) {
window.location.href = $link.data('authed-url') || '/weibo';
} else {
window.location.href = $link.data('unauthed-url') || '/login';
}
}).fail(function() {
window.location.href = '/login?error=network';
});
});
| 方法 | 歷史記錄 | 後退行為 | 適用場景 |
|---|---|---|---|
| `location.href = url` | 新增記錄 | 可後退到原頁 | 常規導航 |
| `location.assign(url)` | 新增記錄 | 可後退 | 語義更明確,函數式 |
| `location.replace(url)` | 替換當前 | **不可後退** | 登錄後跳轉、支付完成、防重複提交 |
條件跳轉核心邏輯:`事件 → 阻止默認 → 判斷狀態 → 設置 location`。推薦非侵入式綁定 + 數據屬性配置 + `location.assign/replace` 語義化導航。避免 `href="javascript:..."` 反模式,保持 HTML 可訪問性與降級能力。