JAVASCRIPT - 未捕获的类型错误:无法读取 null 的属性“值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11928205/
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-26 14:47:30  来源:igfitidea点击:

JAVASCRIPT - Uncaught TypeError: Cannot read property 'value' of null

javascripthtml

提问by George Sumpster

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
        <title>Javascript Form Testing</title>
</head>

<body>
Name: <input type="text" name="Name" value="Name" id="fname"> <br>
Email: <input type="text" name="Email" value="Email" id="mail" > <br>
Phone: <input type="text" name="Number" value="Phone Number" id="dvr" onchange="validatePhone();">
<span id="phoneval"> ?</span>

    <script type="text/javascript">
    phonenum = document.getElementById("dvr").value.length;
       function validatePhone() {
            if (phonenum == 10){
                document.getElementById('phoneval').innerhtml="<-- Valid";
            }
            else{
                document.getElementById('phoneval').innerhtml="<-- Not Valid";
            }
        }
    </script>
</body>
</html>

Hi, I was getting the error 'Uncaught TypeError: Cannot read property 'value' of null' when the tag was in the head, but since I moved it, it went away. However, now it outputs no error and does NOTHING. Please help?

嗨,当标签位于头部时,我收到错误“未捕获的类型错误:无法读取 null 的属性‘值’”,但由于我移动了它,它消失了。但是,现在它没有输出错误并且什么也不做。请帮忙?

Sorry for any formatting and things, new :/

抱歉任何格式和事情,新的:/

回答by Adam Heath

Edit:

编辑:

Slightly different implementation that works: http://jsfiddle.net/SfTR2/Make sure the JS is loaded after the HTML, or use window.onload

稍微不同的实现:http: //jsfiddle.net/SfTR2/确保在 HTML 之后加载 JS,或者使用window.onload

Original answer:

原答案:

You need to get the length within the validation function:

您需要在验证函数中获取长度:

   function validatePhone() {
        var phonenum = document.getElementById("dvr").value.length; //MOVE IT HERE
        if (phonenum == 10){
            document.getElementById('phoneval').innerHTML="<-- Valid";
        }
        else{
            document.getElementById('phoneval').innerHTML="<-- Not Valid";
        }
    }

As previously you were caching the empty length.

如前所述,您正在缓存空长度。

Also, as @su mentioned, you need to use innerHTML

另外,正如@su 提到的,您需要使用 innerHTML

回答by su-

add

添加

validatePhone();

to the end of the script (you defined the function but never called it). And change innerhtml to innerHTML

到脚本的末尾(您定义了函数但从未调用过它)。并将innerhtml更改为innerHTML