我已经能够在按钮单击时动态添加一层输入的表单部分。这个新的div附加在前面的div之后,我试图做一个按钮,如果用户不需要它也可以删除这个层。动态删除输入/ DOM错误
我的问题是我似乎无法删除div。我可以添加但不能删除。当我查看DOM时,可以看到何时单击addDiv按钮,它确实添加了div,并且所有内容都在div内,因此它正在被正确地附加。但是,当我尝试删除新追加的DIV从它的父元素,我抛出了以下错误:
addJob.js:18 Uncaught TypeError: Cannot read property 'parentNode' of undefinedremoveJob @ addJob.js:18onclick @ index.html:1
我不确定如何做的方式,只是如何反向定义我removeJob()
功能它被添加了。
CodePen:http://codepen.io/theodore_steiner/pen/WGEmGr
var i = 0;
function addJob() {
if (i <= 1) {
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_' + i + '"> '+
'<input type="text" class="three-lines" name="position_' + i + '"> '+
'<input type="text" class="three-lines" name="years_' + i + '">'+
'<input type="button" value="-" onclick="removeJob()">';
document.getElementById("employmentHistory").appendChild(div);
}
}
function removeJob(div) {
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
button {
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
}
input[type="button"] {
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
}
input[type="button"]:focus {
outline: none;
}
input.three-lines {
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;
}
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
也许是因为你没有发送一个参数来移除工作? – Lidaranis
在编辑器中使用'<>'按钮添加一个片段。修复在控制台显示的错误 - 它缺少的东西:'removeJob(this)' – mplungjan
我已经更新了我的答案... –