javascript 无法设置未定义或空引用的属性“innerHTML”

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

Unable to set property 'innerHTML' of undefined or null reference

javascript

提问by Jane wang

Get this strange error. I am learning javaScript and copy the code from somewhere and run it but get the error. Here is the code. Change the empty string to any other thing like "Test" I will still get the same error.

得到这个奇怪的错误。我正在学习 javaScript 并从某处复制代码并运行它但出现错误。这是代码。将空字符串更改为“测试”之类的任何其他内容,我仍然会遇到相同的错误。

 <script>

    function theAge() {
        var message, x;
        message = document.getElementById("message");
        message.innerHTML = "";
        x = document.getElementById(age).value;
        try {
            x=Number(x);
            if(x=="") throw "is empty";
            if(isNaN(x)) throw "is not a number";
            if(x>10) throw "is too high";
            if(x<5) throw "is too low";
        }
        catch (err) {
            message.innerHTML = "input" + err;
        }
    }
</script>

回答by Michael Coleman

Looks like you have a typo here

看起来你在这里有一个错字

x = document.getElementById(age).value;

try

尝试

x = document.getElementById("age").value;

回答by nanndoj

You must have an element for message and one for age in your html. And also put the age term between ""

您的 html 中必须有一个用于消息的元素和一个用于年龄的元素。并且还把年龄术语放在""

See it working here

看到它在这里工作

HTML Example:

HTML 示例:

<div>
    Age: <input type="text" id="age" /> </br>
    Message: <div id="message"> </div> </br>
    <button onclick="theAge()">Click</button>
</div>

JS code

JS代码

function theAge() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("age").value;
    try {
        x=Number(x);
        if(x=="") throw "is empty";
        if(isNaN(x)) throw "is not a number";
        if(x>10) throw "is too high";
        if(x<5) throw "is too low";
    }
    catch (err) {
        message.innerHTML = "input" + err;
    }
}

回答by Ershad

you are using server control... use jQuery method

您正在使用服务器控件...使用 jQuery 方法

$("#controlID").html();

$("#controlID").html();