声明为真时,为什么JS不重定向网页?

时间:2019-02-22 08:54:02

标签: javascript if-statement window.location

我输入了一个用户名和一个密码。当用户名和/或密码不匹配时,我会成功获取“警报”,但是当它们匹配时,则不会发生任何事情。我不知道自己在做什么错。

我也尝试过windows.location.replace,结果相同。

function user1() {
    var user = document.getElementById('username').value
    var pass = document.getElementById('password').value
  
    if (user == "admin" && pass == "password1") {
        window.location ("http://stackoverflow.com");
    }
    else {
        alert('incorrect username or password')
    }
}
<form>
    <label for="username" id="user">User</label>
    <input type="text" placeholder="Username" name="username" id="username">
    <br>
    <label for="password">Pass</label>
    <input type="password" name="password" id="password" placeholder="Password">
    <br>
    <button onclick="user1()">Submit</button>
</form>

3 个答案:

答案 0 :(得分:3)

应该是

window.location = 'http://stackoverflow.com';

代替函数调用。另一个问题是导致页面重新加载的按钮。要解决此问题,您应该执行以下操作:

<button type="button" onclick="user1()">Submit</button>

type="button"将阻止其默认提交表单。


演示

function user1() {
  var user = document.getElementById('username').value
  var pass = document.getElementById('password').value
  
  if (user == "admin" && pass == "password1") {
  	window.location = "http://stackoverflow.com";
  }
  else {
    alert('incorrect username or password');
  }
}
<form>
  <label for="username" id="user">User</label>
  <input type="text" placeholder="Username" name="username" id="username">
  <br>
  <label for="password">Pass</label>
  <input type="password" name="password" id="password" placeholder="Password">
  <br>
  <button type="button" onclick="user1()">Submit</button>
</form>

答案 1 :(得分:2)

window.location="url"

function user1() {
  var user = document.getElementById('username').value
  var pass = document.getElementById('password').value
  
  if (user == "admin" && pass == "password1") {
  	window.location="http://stackoverflow.com";
}

  else {
    alert('incorrect username or password')
  }
}
<form>
				<label for="username" id="user">User</label>
				<input type="text" placeholder="Username" name="username" id="username">
				<br>
				<label for="password">Pass</label>
				<input type="password" name="password" id="password" placeholder="Password">
				<br>
				<button onclick="user1()">Submit</button>
			</form>

答案 2 :(得分:0)

假设您正在寻找window.open,其中window.location也可以使用

function user1() {
  var user = document.getElementById('username').value
  var pass = document.getElementById('password').value

  if (user == "admin" && pass == "password1") {
    window.open("https://stackoverflow.com");
  } else {
    alert('incorrect username or password')
  }
}
<form>
  <label for="username" id="user">User</label>
  <input type="text" placeholder="Username" name="username" id="username">
  <br>
  <label for="password">Pass</label>
  <input type="password" name="password" id="password" placeholder="Password">
  <br>
  <button onclick="user1()">Submit</button>
</form>