我创建了一个包含 HTML、CSS 和 Javascript 的列表,您可以在下面看到。
它工作正常,直到我按“清除”并且列表被清除,并且清除按钮也消失了。
我仍在学习 Javascript,不确定我的代码中有什么问题。有人可以帮忙我需要添加/删除哪一行代码来阻止此错误的发生吗?
(() => {
const listElement = document.getElementById('wishlist');
const newItem = document.getElementById('newItem');
const addBtn = document.getElementById('addBtn');
const clearBtn = document.getElementById('clearBtn');
//add new destination to the list
function addItem(item) {
const itemElement = document.createElement('li');
itemElement.textContent = item;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'x';
itemElement.appendChild(deleteButton);
deleteButton.addEventListener('click', ev => { // <- new
listElement.removeChild(itemElement); // <- new
}); // <- new
listElement.appendChild(itemElement);
};
function clearList() {
while (listElement.firstChild) {
listElement.removeChild(listElement.firstChild);
}
}
function renderList(list) {
list.forEach(addItem);
}
addBtn.addEventListener('click', ev => {
newItem.value.split(',').forEach(v => {
if (v) {
addItem(v);
}
});
newItem.value = null;
});
clearBtn.addEventListener('click', ev => {
clearList();
});
window.addEventListener('beforeunload', ev => {
const items = [...listElement.childNodes];
if (items.length) {
const list = items.map(item => {
return item.textContent.slice(0, -1);
});
localStorage.setItem('destination-list', list);
} else {
localStorage.removeItem('destination-list');
}
});
window.addEventListener('DOMContentLoaded', ev => {
const shoppingList = localStorage.getItem('destination-list');
if (destinationList) {
renderList(destinationList.split(','));
}
});
newItem.addEventListener("keyup", ev => {
if (ev.key === "Enter") {
addBtn.click();
}
});
})()
ibeautiful
莫回无
相关分类