未捕获的TypeError:无法读取null的属性值

时间:2014-09-08 19:35:12

标签: javascript jquery uncaught-typeerror

我是jQuery的新手,我试图创建一个登录表单,当用户输入一个简短的用户名时切换文本。所以这是我的代码,当我点击按钮时没有任何反应。我检查了控制台,它在我的代码中的特定行上显示了标题上的错误。我已经检查了可能的错别字,但我没有看到任何错误。所以这是我的代码:

<!DOCTYPE HTML>
<html>
<head>
    <script type="text/javascript" src = "jquery-2.1.1.min.js"></script>
     <script  type="text/javascript">
        var usr = document.getElementById("textbox1").value;//error is over this line.
        if(usr.length<=6){
        $(document).ready(function(){
            $("#press").click(function(){
            $("#warning").toggle();
            });
        });
        }
     </script>
</head>
<body>
    <div id = "middleBlock">
            <form>

                <p id = "username"> Username </p>
                <p id = "password"> Password </p>
                <input type="text" name="user" id="textbox1">
                <input type="password" name="pass" id="textbox2">
                <input type = "button" value = "LOG IN" id = "press">                       
                <p id = "note"> Note: Use the username and password provided by your department. </p>
                <div id = "warning" style = "display:none;padding:3%;">Username too short.</div>
            </form>
        </div>  
</body>

1 个答案:

答案 0 :(得分:6)

script移动到body的末尾或将其包装在DOM就绪函数中。在呈现页面之前,getElementById正在执行,因此会抛出空错误。

示例:

$(document).ready(function(){
    var usr = document.getElementById("textbox1").value;//error is over this line.
    if(usr.length<=6){
        $("#press").click(function(){
            $("#warning").toggle();
        });
    }
 });