密码检查 无法读取 null 的属性“父节点”



所以我正在尝试使用 Javascript 将一个div 插入到另一个div 中,如果 2 个给定的密码不匹配。但是,每次我尝试运行它时,它都会在这篇文章的标题中抛出错误。我只希望div 在 2 个密码匹配时消失。

function passwordMismatchError(){
    var pwrd1 = document.getElementById('password').value;
    var pwrd2 = document.getElementById('password-confirmation').value;
    if(pwrd1 != pwrd2){
        // If there is an error box already
        if(document.getElementById("password-mismatch-error")){
            return;
        }
        // If there isn't an error box
        else{
            errcount++;
            var innerdiv = document.createElement('div');
            innerdiv.setAttribute("id", "password-mismatch-error");
            innerdiv.innerHTML = "<p>ERROR: Passwords don't match.</p>";
            (document.getElementById("error-display")).appendChild(innerdiv);
        }
    }
    else{
        // If the passwords match
        errcount--;
        var innerdiv = document.getElementById("password-mismatch-error");
        console.log(innerdiv);
        innerdiv.parentNode.removeChild(innerdiv);
        return;
    }
}

在外部else语句中,#password-mismatch-error永远不会添加到 DOM 中,因此innerdiv将是未定义的。因此,您无法访问其parentNode

要解决此问题,只需检查该元素是否存在,然后再尝试使用 if(document.getElementById("password-mismatch-error")) 删除其父元素:

function passwordMismatchError(){
    var pwrd1 = document.getElementById('password').value;
    var pwrd2 = document.getElementById('password-confirmation').value;
    if(pwrd1 != pwrd2){
        // If there is an error box already
        if(document.getElementById("password-mismatch-error")) {
            return;
        }
        // If there isn't an error box
        else{
            errcount++;
            var innerdiv = document.createElement('div');
            innerdiv.setAttribute("id", "password-mismatch-error");
            innerdiv.innerHTML = "<p>ERROR: Passwords don't match.</p>";
            (document.getElementById("error-display")).appendChild(innerdiv);
        }
    }
    else{
        // If the passwords match
        errcount--;
        // Ensure the error message actually exists in the DOM
        if(document.getElementById("password-mismatch-error")) {
            var innerdiv = document.getElementById("password-mismatch-error");
            console.log(innerdiv);
            innerdiv.parentNode.removeChild(innerdiv);
        }
        return;
    }
}

希望这有帮助! :)

最新更新