2014-09-23 82 views
2

我从type=click切换到type=submit,以便我可以使用Enter键登录。无效用户名/密码的if/else语句正常工作。但是,如果我输入正确的凭据,它不会加载位置(不同的HTML页面)。onSubmit按钮将不会加载位置

PS:我是新来的编码一般(只有3周)尝试解释它,所以一个新手会知道。 在此先感谢。

<script type="text/javascript"> 
    function check_info(){ 
     var username = document.login.username.value; 
     var password = document.login.password.value; 

     if (username=="" || password=="") { 
      alert("Please fill in all fields") 
     } else { 
      if(username=="test") { 
       if (password=="test") { 
        location="Random.html" 
       } else { 
        alert("Invalid Password") 
       } 
      } else { 
       alert("Invalid Username") 
      } 
     } 
    } 
</script> 

<form name=login onsubmit="check_info()"> 
    Username: 
    <input type="text" name="username" id="username"/> 
    <br> 
    Password: 
    <input type="password" name="password" id="password"/> 
    <br> 
    <br> 
    <input type="submit" value="Login"/> 
</form> 

回答

1

两件事情:

- Proper way to simulate a clink on a link是利用改变locationhref属性,而不是location本身。下面这行应该工作:

window.location.href = "Random.html"; 


- 当你被重定向到另一个页面,你要 “抑制”(停止)自然onsubmit事件。

换句话说,你必须对onsubmit事件returnfalse,否则重定向(至Random.html)将不会有一个工作的机会,因为提交事件会踢(和sedn用户在action页面在重定向工作之前)。

因此改变<form name=login onsubmit="check_info()">到:

<form name=login onsubmit="return check_info()"> 

,并添加一个return false;check_info()结束。

完整的代码应该如下:

<script type="text/javascript"> 
    function check_info(){ 
     var username = document.login.username.value; 
     var password = document.login.password.value; 

     if (username=="" || password=="") { 
      alert("Please fill in all fields") 
     } else { 
      if(username=="test") { 
       if (password=="test") { 
        window.location.href = "Random.html"; // ------ CHANGED THIS LINE 
       } else { 
        alert("Invalid Password") 
       } 
      } else { 
       alert("Invalid Username") 
      } 
     } 
     return false; // ------------------------ ADDED THIS LINE 
    } 
</script> 

和HTML(只有onsubmit改变):

<form name="login" onsubmit="return check_info()"> 
    Username: 
    <input type="text" name="username" id="username"/> 
    <br> 
    Password: 
    <input type="password" name="password" id="password"/> 
    <br> 
    <br> 
    <input type="submit" value="Login"/> 
</form> 

JSFiddle demo here

+0

嘿,非常感谢您的帮助!完美工作。 – SongJaeGu 2014-09-23 20:22:29

+0

嗨@SongJaeGu如果这个或任何答案已经解决了您的问题,请点击复选标记,考虑[接受它](http://meta.stackexchange.com/a/5235/219205)。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 – acdcjunior 2014-09-28 21:35:59

+0

糟糕,我的坏。干得好! ;) – SongJaeGu 2014-09-29 23:57:55

2

您需要在location

location.href = "Random.html"; 

(还可以使用.href,既然你说你是新的,可以肯定的编写JavaScript和测试时,要注意,开发者控制台(F12)开 - 你” LL抓到很多的错误很早就)

0

这样做的新途径 - 在该行

if(username=="test") { 
设置断点

然后逐步找出问题所在。

这样做的旧派方式(在我们开始使用Javascript调试器之前)是要在每个块中提醒消息,并找出为什么你先进入该块。这比调试器复杂得多,但有时你可能需要诉诸旧式的黑客手段。