因此,如果两个给定的密码不匹配,我尝试使用Javascript将一个div插入到另一个div中。然而,每次我尝试运行它时,它都会在这篇文章的标题中抛出错误。如果两个密码匹配,我只想让div消失。
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;
}
}发布于 2017-11-07 10:37:30
在外部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;
}
}希望这能有所帮助!:)
https://stackoverflow.com/questions/47149058
复制相似问题