第一次,密码字段

时间:2017-10-04 22:00:22

标签: javascript html

现在已经解决了。

它基本上是一个文本框,当输入正确的文本时应该会发生一些事情,我有代码,这是我第一次玩html。它并不适合任何事情而只是为了好玩

<body>
    <center>
        <input id="passfield" type="text" value="" />
        <input id="check" type="button" value="Check" onclick="check();"/>
        <script>
            var field = document.getElementById("passfield").value;
            var pass = "password";
            function check() {
                if field === pass then {
                    window.location.href = 'the site i want it to go to';
                }; 
            };
            document.getElementById("check").onclick = check();
        </script>
    <center>
</body>

控制台说:check() isn't a function

1 个答案:

答案 0 :(得分:2)

你有几个问题:

  • 您应该将变量fieldpass移动到函数中,以便在调用函数时定义它们。否则,它们将不会更新 - 这意味着field将始终为空(因为它在页面加载时设置,当输入的值为''时)

  • 在您的Javascript中添加事件侦听器,而不是使用“onclick”属性。它更好,因为它可以将所有Javascript保存在一起,并且每次遇到JS错误时都不必浏览HTML。

您有一些格式问题 - 特别是if应使用以下语法:

if (condition) {
 then do this
} else {
  do this
}

您可以查看this example on CodePen

<body>
  <center>
    <input id="passfield" type="text" value="" />
    <input id="check" type="button" value="Check" />
    <center>
      <script>
        function check() {
          var field = document.getElementById("passfield").value;
          var pass = "password";
          if (field === pass) {
            window.location.href = "the site i want it to go to";
          }
        }
        document.getElementById("check").addEventListener('click', check)
      </script>
</body>
相关问题