我正在尝试创建一个简单的登录示例,其中如果登录详细信息符合特定的用户名和密码,则在 3 秒后重定向到不同的页面。
这是我到目前为止所尝试的,感谢任何帮助
<input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>
<input type="password" id="password" placeholder="Password" name="psw" maxlength="25" required>
<div id="loginButton">
<button type="button" input id="detailsChecker" onclick="showalert('alert');" label=>Login </button>
</div>
<div id="alert" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p id="alertmsg"> </p>
</div>
<div id="alertsuccess" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p id="alertmsg"> </p>
function showalert(id) {
var divelement = document.getElementById(id);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "u1460714" && password ==="barney") {
document.getElementById("alertmsg").innerHTML = "Successfully logged in, redirecting in 3 seconds";
setTimeout, window.location = "attendance.html"; 3000;
divelement.style.display = 'block';
divelement.className = 'success'
}
}
最佳答案
您错误地调用了setTimeout()
函数。它接受一个回调函数作为参数,保存必须延迟的整个代码。
function showalert(id) {
var divelement = document.getElementById(id);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "u1460714" && password === "barney") {
document.getElementById("alertmsg").innerHTML = "Successfully logged in, redirecting in 3 seconds";
setTimeout(function() {
window.location = "attendance.html";
}, 3000);
divelement.style.display = 'block';
divelement.className = 'success'
}
}
<input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>
<input type="password" id="password" placeholder="Password" name="psw" maxlength="25" required>
<div id="loginButton">
<button type="button" input id="detailsChecker" onclick="showalert('alert');" label=>Login </button>
</div>
<div id="alert" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p id="alertmsg"> </p>
</div>
<div id="alertsuccess" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p id="alertmsg"> </p>
关于javascript - onclick 如果满足条件则使用 setTimeout 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741007/