我正在尝试制作一个待办事项列表,在该列表中,您可以动态地附加一个删除按钮,该按钮与父div中的每个新添加的元素一起出现。单击删除按钮将仅用于删除相应的新元素
这适用于列表上的最后一个项目,但当我试图删除其他项目时,控制台会说它的父节点为null。
关于这里发生的事情有什么建议吗?
var input = document.getElementById("boxInput");
var output = document.getElementById("output")
var submit = document.getElementById("submit")
var i = 0;
function addElement(parentId, elementTag, elementId, html) {
var output = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
output.appendChild(newElement)
}
function removeElement(elementId) {
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
var itemId = 0;
function additem() {
i += 1
itemId++;
const btn = document.createElement("button");
btn.onclick = function() {}
var html = i + ". " + input.value + " " + `<button onclick="javascript:removeElement('item-' + itemId + ''); return false;">X</button>`;
addElement("output", "p", ("item-" + itemId), html);
return itemId
}
submit.addEventListener("click", additem);
#box {
margin:auto;
border-width: 3px;
border-radius:5px;
border-color:black;
border-style:solid;
width:300px;
height:100px;
margin-top:200px;
line-height:100px;
display:flex;
justify-content:center;
align-items:center;
}
#boxInput {
width:150px;
text-align:center;
margin-right:5px;
}
#output {
margin-top:20px;
width:100%;
text-align:center;
}
h1 {
margin:center;
text-align:center;
position:relative;
top:190px;
}
.delete {
margin-left:5px;
}
<h1>To Do List!</h1>
<div id="box">
<input id="boxInput" placeholder="add an item"/>
<button id="submit">Submit</button>
</div>
<div id="output">
</div>
不需要itemId
或类似的东西。只需为每个待办事项创建一个div
。向其中添加一个<button>
和<span>
。向按钮添加事件侦听器,在该按钮中,您可以从output
元素中删除整个tododiv
var input = document.getElementById("boxInput");
var output = document.getElementById("output")
var submit = document.getElementById("submit")
function additem() {
const todo = document.createElement('div');
const btn = document.createElement('button');
btn.innerHTML = "Remove"
const text = document.createElement('span');
text.innerHTML = input.value;
todo.appendChild(text);
todo.appendChild(btn);
btn.addEventListener('click', (e) => {
output.removeChild(todo)
})
output.appendChild(todo)
}
submit.addEventListener("click", additem);
#box {
margin:auto;
border-width: 3px;
border-radius:5px;
border-color:black;
border-style:solid;
width:300px;
height:100px;
margin-top:200px;
line-height:100px;
display:flex;
justify-content:center;
align-items:center;
}
#boxInput {
width:150px;
text-align:center;
margin-right:5px;
}
#output {
margin-top:20px;
width:100%;
text-align:center;
}
h1 {
margin:center;
text-align:center;
position:relative;
top:190px;
}
.delete {
margin-left:5px;
}
<h1>To Do List!</h1>
<div id="box">
<input id="boxInput" placeholder="add an item"/>
<button id="submit">Submit</button>
</div>
<div id="output">
</div>