这是我的代码,这一行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);
});
请注意,任何涉及要求用户浏览器自行授权的密码系统都是毫无意义的。