2015-04-03 62 views
1

对不起,第一次玩这个。这里的HTML:更多简单的密码系统的东西

<!DOCTYPE html> 
<html> 
<head> 
    <title>SuM BUTtonsS DOe</title> 
    <link rel="stylesheet" href="buttons.css"/> 
</head> 
<body> 
    <p>Please enter the password</p> 
    <form id="enter" onSubmit="javascript:passCheck()"> 
     <input id="password" type="password" placeholder="Password"> 
    </form> 
    <p id="incorrect"><em>INCORRECT PASSWORD</em></p> 

    <script type="text/javascript"> 
     function passCheck() { 
      var input = document.getElementById('password').value; 

      if (input == 'herro') { 
       window.alert("IT WORKS!!"); 
      } 
      else { 
       var incorrect = document.getElementById('incorrect'); 
       incorrect.style.display = "block"; 
      } 
     } 
    </script> 
</body> 
</html> 

当我输入了错误的密码,错误密码出现,但只有一小会儿。然后它又走了。不知道为什么。

UPDATE:

<!DOCTYPE html> 
<html> 
<head> 
    <title>SuM BUTtonsS DOe</title> 
    <link rel="stylesheet" href="buttons.css"/> 
</head> 
<body> 
    <p>Please enter the password</p> 
    <form id="enter" onSubmit="javascript:passCheck()"> 
     <input id="password" type="password" placeholder="Password"> 
    </form> 
    <p id="incorrect"><em>INCORRECT PASSWORD</em></p> 

    <script type="text/javascript"> 
     function passCheck() { 
      var input = document.getElementById('password').value; 

      if (input == 'herro') { 
       window.alert("IT WORKS!!"); 
      } 
      else { 
       var incorrect = document.getElementById('incorrect'); 
       incorrect.style.display = "block"; 
       return false; 
      } 
     } 
    </script> 
</body> 
</html> 
+1

可能无关,但客户端(浏览器)端的密码验证不会飞 - 您需要将密码(使用HTTPS)发布到服务器以做出该决定。 – StuartLC 2015-04-03 17:12:28

+0

你可以发布一个codepen或jsfiddle吗? – 2015-04-03 18:24:51

+0

StuartLC是的,我知道,这只是一个基本的小练习。但是,谢谢! – Tommay 2015-04-03 18:28:57

回答

2

在提交表单将触发默认操作,在这种情况下是将内容提交到同一个页面(因为缺乏一个action财产)。

因此,您所看到的是JavaScript运行并更改样式以显示错误消息,然后重新加载页面。

为了确保页面不重新加载return falsepassCheck的末尾。更好的办法是使用addEventListenerevent.preventDefault(),但这有点多。

+0

没有工作。我用代码更新了问题 - 是你的意思? – Tommay 2015-04-03 17:21:27

0
<p>Please enter the password</p> 
<form id="enter" onSubmit="passCheck(); return false;"> 
    <input id="password" type="password" placeholder="Password"> 
    <input type="submit" value="Submit"/> 
</form> 
<p id="incorrect" style="display: none"><em>INCORRECT PASSWORD</em></p> 

<script type="text/javascript"> 
    function passCheck() { 
     var input = document.getElementById('password').value; 

     if (input == 'herro') { 
      window.alert("IT WORKS!!"); 
     } 
     else { 
      var incorrect = document.getElementById('incorrect'); 
      incorrect.style.display = "block"; 
     } 
    } 
</script> 
+0

将验证绑定到按钮的“click”事件并不是一个好主意。您可以在焦点位于密码字段时按下'enter'来提交表单,在这种情况下不会发生任何事情。在提交事件上进行验证更为正确。 – Halcyon 2015-04-03 17:14:16