javascript 未捕获的类型错误:无法读取 null 的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25731803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:55:31  来源:igfitidea点击:

Uncaught TypeError : Cannot Read property value of null

javascriptjquerytypeerror

提问by ejandra

I am new to jQuery and im trying to create a login form that toggles a text when the user inputs a short username. So here is my code and when i click on the button nothing happens. I checked the console and it says the error on the title over at the particular line in my code.I've checked for possible typos too but i didn't see any. So here is my code :

我是 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>

回答by tymeJV

Move your scriptto the end of the bodyor wrap it in a DOM ready function. Your getElementByIdis executing before the page is rendered, thus throwing a null error.

将您的移动script到 的末尾body或将其包装在 DOM 就绪函数中。您getElementById正在呈现页面之前执行,从而引发空错误。

Example:

例子:

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