为什么我的重定向代码不起作用,但我的警报起作用?请更正我的代码并检查



这是我的代码,这一行window.location = "https://www.google.com";不工作,但alert完全工作。请帮帮我。谢谢!

<!DOCTYPE html>
<html>
</html>
<head>
<title>Document</title>
</head>
<body>
<form>
<label for="pswd">Enter your password: </label>
<input type="password" id="myInput" autofocus>
<input type="submit" id="myBtn" value="Submit" onclick="checkPswd();">
</form>
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "admin";
var password = document.getElementById("myInput").value;
if (password == confirmPassword) {
window.location = "https://www.google.com";
// alert("correct");
}
else {
alert("Password");
}
}       
</script>
</body>        
</html>

分配给window.location会触发导航,但随后JS命令完成,正常表单提交继续,从而触发导航到表单的action(取消之前的导航指令(。

您需要取消默认行为。

通常,这样做的方法是将事件侦听器绑定到表单的提交事件(并且而不是按钮的单击事件(。

例如

function checkPswd(event) {
event.preventDefault();
// etc...
}
addEventListener('DOMContentLoaded'), () => {
document.querySelector('form').addEventListener('submit', checkPswd);
});

请注意,任何涉及要求用户浏览器自行授权的密码系统都是毫无意义的。

最新更新