javascript - 为什么当语句为 true 时 JS 不会重定向网页?

标签 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>

最佳答案

应该是

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>

关于javascript - 为什么当语句为 true 时 JS 不会重定向网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54823281/

相关文章:

javascript - 调用 API url 参数问题

javascript - 如何使用javascript获取没有id和name字段的输入框的值

excel - 如何在我的公式中的数据输入 Excel 之前将我的结果字段保持空白?

javascript - 在 Javascript 中,如何向函数 Change() 添加附加语句?

javascript - 通过 window.location.host 比较 URL?

javascript - typescript - 删除毫秒

c - 如果 C 中的语句没有正确评估?

jquery - 将 window.location 添加到 body 类

javascript - 使用 javascript 显示隐藏的 HTML 元素