否则,如果没有正常工作Javascript

时间:2016-11-22 10:39:08

标签: javascript if-statement

<body style="text-align:center;">
        <form>
        <label id="agefield" for="age">age:</label><input id="age" type="text" maxlength="2" />
        <button id="subButton" class="button" >Enter</button>
        <p id="result"></p>
        <script>
            function age() {
                var age= document.getElementById('age').value;
                var result= document.getElementById('result');

                if (age>=18) {
                    result.textContent = 'You Must be 18 and above to enter';
                }
                else {
                    result.textContent = 'Welcome click <a href=#> here </a> to enter xguineapig';
                }
            }
            document.addEventListener("DOMContentLoaded", function(event) {
            var el = document.getElementById('subButton');
                el.addEventListener('click', age, false);
            });
        </script> 
    </body>

1 个答案:

答案 0 :(得分:4)

如果您要显示该消息,则必须检查<18是否为>=

否则,请使用innerHTML代替textContent正确显示<a>

而且,正如其他人所评论的那样,请关闭form标记。

PS:下次在您的问题中提供更多详细信息时,人们不应该猜测您要求的内容。

&#13;
&#13;
<body style="text-align:center;">
  <form>
    <label id="agefield" for="age">age:</label>
    <input id="age" type="text" maxlength="2" />
    <button id="subButton" class="button">Enter</button>
  </form>
  <p id="result"></p>
  <script>
      function age() {
        var age = document.getElementById('age').value;
        var result = document.getElementById('result');

        if (age < 18) {
          result.innerHTML = 'You Must be 18 and above to enter';
        } else {
          result.innerHTML = 'Welcome click <a href=#> here </a> to enter xguineapig';
        }
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        var el = document.getElementById('subButton');
        el.addEventListener('click', age, false);
      });
  </script>
</body>
&#13;
&#13;
&#13;