我有这个简单的待办事项列表,它接受一些输入,然后在下面,它显示文本旁边有一个复选框。我试图弄清楚如何为每个删除项目的项目添加一个按钮。
function onReady() {
const addToDoForm = document.getElementById('addToDoForm');
const newToDoText = document.getElementById('newToDoText');
const toDoList = document.getElementById('toDoList');
addToDoForm.addEventListener('submit', event => {
event.preventDefault();
let title = newToDoText.value;
let newLi = document.createElement('li');
let checkbox = document.createElement('input');
checkbox.type = "checkbox";
newLi.textContent = title;
newLi.appendChild(checkbox);
toDoList.appendChild(newLi);
newToDoText.value = '';
});
}
window.onload = function() {
alert("The window has loaded!");
onReady();
};
<form id="addToDoForm">
<label for="newToDoText">New To-Do:</label>
<input type="text" id="newToDoText">
<button type="submit">Add To-Do!</button>
</form>
<ul id="toDoList">
</ul>
<script src="app.js"></script>
答案 0 :(得分:0)
只需要创建另一个元素,在本例中为一个按钮,然后添加一个单击处理程序来删除父元素。
function onReady() {
const addToDoForm = document.getElementById('addToDoForm');
const newToDoText = document.getElementById('newToDoText');
const toDoList = document.getElementById('toDoList');
function onDelete(e) {
e.target.parentElement.outerHTML = "";
}
addToDoForm.addEventListener('submit', event => {
event.preventDefault();
let title = newToDoText.value;
let newLi = document.createElement('li');
let checkbox = document.createElement('input');
let del = document.createElement('button');
del.textContent = "delete";
del.onclick = onDelete;
checkbox.type = "checkbox";
newLi.textContent = title;
newLi.appendChild(checkbox);
newLi.appendChild(del);
toDoList.appendChild(newLi);
newToDoText.value = '';
});
}
window.onload = function() {
alert("The window has loaded!");
onReady();
};