代碼中直接在 function dl() 內寫 window.location.href = "..." 卻不跳轉,原因通常是函數未被調用或調用時機錯誤。
<script>
$(document).ready(function(){
$("#tjan").click(function(){
window.open('https://www.baidu.com')
})
})
function dl() {
var a = document.getElementById("yhm").value;
var f = $("#mima").val();
// 這裡寫跳轉但從未調用 dl()
}
window.location.href = "https://www.baidu.com"; // 這行在全局執行,頁面加載即跳轉
</script>
<script>
function dl() {
var username = document.getElementById("yhm").value;
var password = $("#mima").val();
// 業務邏輯驗證...
if (!username || !password) {
alert("請輸入完整信息");
return;
}
// 構建帶參數的 URL
var url = "https://www.example.com/login?user=" + encodeURIComponent(username)
+ "&pwd=" + encodeURIComponent(password);
// 方式 1:當前頁跳轉
window.location.href = url;
// 方式 2:新窗口打開
// window.open(url, '_blank');
}
// 綁定按鈕點擊事件
$(document).ready(function() {
$("#loginBtn").click(dl); // 或 $("#loginBtn").on('click', dl);
// 回車鍵提交
$("#yhm, #mima").keypress(function(e) {
if (e.which === 13) dl();
});
});
</script>
<input type="text" id="yhm" placeholder="用戶名">
<input type="password" id="mima" placeholder="密碼">
<button id="loginBtn">登錄跳轉</button>
$(document).ready 內綁定)encodeURIComponent 編碼 URL 參數,防止特殊字符破壞鏈接window.location.href 當前頁跳轉,window.open 新窗口function dl() {
$.post("/api/login", {user: $("#yhm").val(), pwd: $("#mima").val()})
.done(function(res) {
if (res.success) {
window.location.href = res.redirectUrl || "/dashboard";
} else {
alert(res.msg);
}
});
}