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

时间:2018-12-22 21:22:10

标签: javascript html if-statement alert

我一直试图告诉浏览器,在用户关闭警报框后将其重定向到其他位置,但是我尝试过的任何方法似乎都没有用,所以我问您是否可以检查我的代码,并告诉我您是否看到可以满足我需求的解决方案。这段代码只是一个练习,我正在练习和测试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);
    }
}

4 个答案:

答案 0 :(得分: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";
}

希望这会有所帮助!

答案 1 :(得分:0)

您应该尝试以下操作

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

答案 2 :(得分:0)

实际上,您只需要在按钮上添加type =“ button”,您的代码就会起作用:

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

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

答案 3 :(得分: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);
 }
}

相关问题