关闭警报框后如何重定向页面?

问题描述 投票:0回答:4

我一直试图告诉浏览器在关闭警报框后将用户重定向到其他位置,但我尝试过的方法似乎都没有工作,所以我问你是否可以检查我的代码并告诉你如果你看到我的需求可能的解决方案,我。这段代码只是一个练习,我正在练习和测试javascript。

到目前为止,我已尝试使用这些,但没有任何效果。

window.location.href(); 
window.location.replace(); 
window.location.assign(); 
location.href(); 
location.replace(); 
location.assign();

HTML代码:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="javascript.js"></script>
</head>
<body>
<div id="container" align="center"><br />
<form>
Nickname: <input type="text" id="nickname" name="nickname"><br />
Password: <input type="password" id="password" name="password"><br />
<button onclick="login();">Login</button>
</form>
<p id="result:"></p><br />
</div>
</body>
</html>

Javascript代码:

function login(){
    var nickname = document.getElementById("nickname").value;
    var password = document.getElementById("password").value;
    var result = document.getElementById("result");
    var error = "Invalid Credentials!";
    var sucess = "Login Sucess!";

    if (nickname == "neo", password == 123){
        alert(sucess);
        location.assign("welcome.html");
    }
    else if(nickname == 22){
        confirm("Awesome!");
        location.replace("welcome.html");
    }
    else if(nickname == ""){
        alert("Nickname is required!");
    }
    else{
        alert(error);
    }
}
javascript html if-statement alert
4个回答
0
投票

实际上你只需要在按钮上添加type =“button”,你的代码就可以了:

<button type="button" onclick="login();">Login</button>

原因是按钮在表单内自动作为type =“submit”。


2
投票

您应该使用window.location.href作为赋值(使用=)而不是将其作为函数处理(使用()):

if (nickname == "neo", password == 123){
    alert(sucess);
    window.location.href = "welcome.html";
}
else if(nickname == 22){
    confirm("Awesome!");
    window.location.href = "welcome.html";
}

希望这有帮助!


0
投票

你应该尝试以下方法

window.location.href = 'welcome.html';

0
投票

使用此JavaScript代码:

function login(){
 var nickname = document.getElementById("nickname").value;
 var password = document.getElementById("password").value;
 var result = document.getElementById("result");
 var error = "Invalid Credentials!";
 var sucess = "Login Sucess!";

 if (nickname == "neo", password == 123){

  if (alert(sucess)) {} else {
   window.location = "welcome.html";
  }
 }
 else if(nickname == 22){
  if (confirm("Awesome!")) {
   window.location = "welcome.html";
  }
 }
 else if(nickname == ""){
  alert("Nickname is required!");
 }
 else{
  alert(error);
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.