未捕获的TypeError:无法设置属性' innerHTML'未定义的不确定为什么会发生

时间:2016-10-24 21:49:45

标签: javascript html

不确定为什么会出现此错误,有人可以帮助我吗?我试图添加window.onLoad = function check(){},它仍然给了我错误代码。我仔细检查过代码:/

check   @   errors.html:43
onclick @   errors.html:18

`

<html>
<head>
<meta charset="utf-8">
<title>Errors</title>
</head>

<body>
<p>Your password should containt atleast 6 characters, 1 number and 1 capital letter!</p>
    <p>Password: <br /> <input id="password" type="password"></p>
    <p>Re-enter Password: <br /> <input id="password2" type="password"><br /></p>
    <button onclick="check()">Submit</button>
    <br />
    <p id="error"></p>
    <script>
        function check() {
            var password = document.getElementById("password").value;
            var password2 = document.getElementById("password2").value;
            var errorMessage = document.getElementById("error").value;
            var errorToThrow = "";

            try {
                if (password.length < 6) {
                    errorToThrow += "<br /> Passsword too short.";
                }
                if (/[A-Z]/g.test(password) == false) {
                    errorToThrow += "<br /> Passsword needs 1 capital letter.";
                }
                if (/\d/g.test(password) == false) {
                    errorToThrow += "<br /> Passsword needs 1 digit.";
                }
                if (password != password2) {
                    errorToThrow += "<br /> Passwords should match.";
                }
                throw errorToThrow;
            } catch(err) {
                errorMessage.innerHTML = err;
            }
        }
</script>
</body>
</html>`

1 个答案:

答案 0 :(得分:1)

        var errorMessage = document.getElementById("error").value;

看起来您要复制/粘贴,但错误消息<p>不会有&#34;值&#34;属性,即使它确实你不想要那个;你想要节点本身:

        var errorMessage = document.getElementById("error");