JavaScript 运行时错误无法获取未定义或空引用的属性“值”

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

JavaScript runtime error Unable to get property 'value' of undefined or null reference

javascriptjquery

提问by Pearl

I'm unable to access the variable in the JS file.

我无法访问 JS 文件中的变量。

The Validation is working fine when written in the same page. But when I pasted the Validation code to a separate JS file, its not working.

在同一页面中编写时,验证工作正常。但是当我将验证代码粘贴到单独的 JS 文件时,它不起作用。

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <script src="Scripts/NewValidation.js" type="text/javascript"></script>
<table id="tblUpdateReg">
        <thead>
            <tr>
                <td>
                    Update Details
                </td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div>
                        Username :
                    </div>
                </td>
                <td>
                    <input type="text" runat="server" id="txtUsername" />
                </td>
            </tr>
</tbody>
</table>
</asp:Content>

JS file:

JS文件:

function Validate() {

    var username= document.getElementById("txtUsername").value;

    if (username== "") {
        alert("username Required.");
        return false;
    }



    return true;

}

Error:JavaScript runtime error: Unable to get property 'value' of undefined or null reference

错误:JavaScript 运行时错误:无法获取未定义或空引用的属性“值”

回答by Emil A.

It means that the element with an id of txtUsername doesn't exist. You execute your script before the element is created.

这意味着id为txtUsername的元素不存在。在创建元素之前执行脚本。

You should either put your script at the bottom of the page or use a

您应该将脚本放在页面底部或使用

window.onload = function() {} 

in which you'll execute your code.

您将在其中执行代码。