如果条件为真,为什么 Javascript window.location 无法重定向页面?

Why Javascript window.location can't redirect page if condition is true?

我刚开始使用 javascript,这是为了测试。 我有带有用户名和密码的基本登录表单,并添加了一些 Javascript 来获取用户名和密码值,检查它们,如果它是真的应该将我重定向到另一个 html 页面。
在这种情况下,我使用了 window.location..

这是代码

function Validate() {
  username = document.login.korisnicko.value;
  password = document.login.lozinka.value;
  
  if (username == "" || password == "") {
   window.alert ("Ne valja");
   return false;
  }
  else if (password.length < 6) {
   window.alert("mora biti duze od 6 slova");
   return false;
  }
  else {
   window.location = "profil.html";
   return true;
  }
 }
<form name = "login">
 <h1 id="greska"></h1>
 <p id="greska2"></p>
 <label>Korisnicko</label> <br>
 <input type ="text" id="korisnicko" name="korisnicko"> <br>
 <label>Lozinka</label> <br>
 <input type ="password" id="lozinka" name="lozinka"> <br>
 
 <button type = "submit" onclick="Validate();">Submit</button>
</form>

这是一个有效的 fiddle: http://jsfiddle.net/uLbycrhm/1/

我不建议使用 window.location 而不是正确的 location.href,也不建议使用 window.alert 而不是 alertwhat's the difference?),所以我也对其进行了调整。在这里使用 return 也是不必要的,因为你的函数绑定到 onclick,而不是 onsubmit.

重要的是要知道 location 是一种对象,这里有一个 link 供您参考:MDN.

您可以使用 return 关键字调用函数

<script>
function Validate() {
        username = document.login.korisnicko.value;
        password = document.login.lozinka.value;

        if (username == "" || password == "") {
            alert ("Ne valja");
            return false;
        }
        else if (password.length < 6) {
            alert("mora biti duze od 6 slova");
            return false;
        }
        else {
            window.location = "profil.html";
            return false;
        }
    }
</script>
<form name = "login" method="REQUEST" action=>
    <h1 id="greska"></h1>
    <p id="greska2"></p>
    <label>Korisnicko</label> <br>
    <input type ="text" id="korisnicko" name="korisnicko"> <br>
    <label>Lozinka</label> <br>
    <input type ="password" id="lozinka" name="lozinka"> <br>

    <button type = "submit" onclick="return Validate();">Submit</button>
</form>