【问题标题】:Why Javascript window.location can't redirect page if condition is true?如果条件为真,为什么 Javascript window.location 无法重定向页面?
【发布时间】:2016-09-05 06:18:32
【问题描述】:

我刚开始使用 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>

【问题讨论】:

  • 你想用值重定向吗?我建议使用 action 属性并从脚本中删除 else 部分。
  • 据我所知,该代码可以工作 - 你看到了什么?

标签: javascript forms login window.location


【解决方案1】:

这是一个有效的小提琴: http://jsfiddle.net/uLbycrhm/1/

我不建议使用window.location 代替正确的location.href,也不建议使用window.alert 代替alert (what's the difference?),所以我也对其进行了调整.这里也不需要使用return,因为您的函数与onclick 绑定,而不是onsubmit。

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

【讨论】:

    【解决方案2】:

    你可以用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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      相关资源
      最近更新 更多