2 回答
TA贡献1993条经验 获得超5个赞
问题是因为您将清除按钮保留在 ol 内,并在按下清除时删除列表的子项,将其移到 ol 之外,它将像下面这样工作:
(() => {
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();
}
});
})()
ol{
padding: 1em 0;
margin: 0;
}
li button {
opacity: 0.05;
transition: 0.4s;
background: none;
border: none;
}
li:hover button {
opacity: 0.4;
}
li button:hover {
opacity: 1;
}
button, input {
font-size: inherit;
}
input {
padding-left: 1em;
flex: 1;
min-width: 5em;
}
#clearBtn{
width: 100%;
}
li button {
opacity: 0.05;
transition: 0.4s;
background: none;
border: none;
}
li:hover button {
opacity: 0.4;
}
li button:hover {
opacity: 1;
}
button, input {
font-size: inherit;
}
input {
padding-left: 1em;
flex: 1;
min-width: 5em;
}
<div class="destination-list">
<h2>Destination Wish List</h2>
<input placeholder="New Destination" id="newItem">
<button id="addBtn">Add</button>
<ol id="wishlist">
</ol>
<button id="clearBtn">Clear</button>
TA贡献1865条经验 获得超7个赞
<div class="destination-list">
<h2>Destination Wish List</h2>
<input placeholder="New Destination" id="newItem">
<button id="addBtn">Add</button>
<button id="clearBtn">Clear</button>
<ol id="wishlist">
</ol>
- 2 回答
- 0 关注
- 122 浏览
添加回答
举报