提问者:小点点

window.location.href在表单-HTML中不工作


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;

共1个答案

匿名用户

除了不在页面中存储userid和密码之外,您还需要使用
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';
  }
});