【问题标题】:window.location.href not working in form-htmlwindow.location.href 在 form-html 中不起作用
【发布时间】:2020-11-17 23:43:25
【问题描述】:

window.location.href 没有重定向用户。
我也尝试过 return true

表格代码:-

<form method="POST" name="main_form" onsubmit="login()">
<input type="email" name="email">
<input type="password" name="pwd">
<input type="submit">
</form>

登录():-

function login() {
    var email = document.main_form.email.value;
    var pwd = document.main_form.pwd.value;
    if (email == 'example@example.com' && pwd == 'example123') {
        sessionStorage.setItem("email", email);
        window.location.href = './index.html';
        return false;

【问题讨论】:

  • 您需要执行onsubmit="return login()" 才能使 return false 起作用
  • 并将 return false 移到 if 之外
  • 谢谢@mplungjan

标签: javascript html forms web


【解决方案1】:

除了不在页面中存储用户名和密码外,您还需要使用
onsubmit="return login()"

function login() {
  var email = document.main_form.email.value;
  var pwd = document.main_form.pwd.value;
  if (email == 'example@example.com' && pwd == 'example123') {
    sessionStorage.setItem("email", email);
    window.location.href = './index.html';
  }
  return false;
}

最好使用事件监听器:

document.querySelector("form[name=main_form]").addEventListener("submit",function(e) {
  e.preventDefault(); // stop submission
  const email = document.main_form.email.value;
  const pwd = document.main_form.pwd.value;
  if (email == 'example@example.com' && pwd == 'example123') {
    sessionStorage.setItem("email", email);
    window.location.href = './index.html';
  }
});

【讨论】:

    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 2014-11-16
    • 2013-08-19
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多