使用DOM从列表中删除项目 [英] Deleting an item from a list using the DOM
问题描述
我是网络开发的新手。我正在学习JS,并且在玩一些代码的同时,我仅使用DOM制作了一个简单的待办事项应用程序。
I'm new to web development. I'm learning JS, and while playing around with some code, I made a simple to-do app with only using the DOM.
我在获取从列表中删除项目的逻辑权利。我正在遍历Dom并使用类似的方法; parentNode,removeChild这样做。之前,我曾尝试过使用n:last-child选择器从列表中删除最后一项的另一种方法,但似乎找不到一种单独删除某项的方法。
I'm having trouble getting the logic right to delete an item from a list. I'm traversing doms and using methods like; parentNode, removeChild to do so. I previously tested another way of deleting the last item from a list using n:last-child selector, but I can't seem to find a way to remove an item individually.
HTML:
<ul>
<li>grapes<span><button class="removeBtn">Remove</button></span></li>
<li>amethyst<span><button class="removeBtn">Remove</button></li>
<li>lavender<span><button class="removeBtn">Remove</button></li>
<li>plums<span><button class="removeBtn">Remove</button></li>
</ul>
JS:
const listDiv = document.querySelector('.listDiv'),
hideBtn = document.querySelector('#hideBtn'),
addItemBtn = document.querySelector('button.addItemBtn'),
addItemInput = document.querySelector('input.addItemInput'),
removeListBtn = document.querySelector('button.removeListBtn'),
removeToDo = document.querySelectorAll('.removeBtn'),
li = document.querySelectorAll('li'),
list = document.querySelector('ul');
//adding an item to list
addItemBtn.addEventListener('click', () => {
let list = document.querySelector('ul'),
newItem = document.createElement('li');
newItem.textContent = addItemInput.value;
if (addItemInput.value !== ''){
list.appendChild(newItem);
addItemInput.value = '';
}
})
//remove last item
removeListBtn.addEventListener('click', () => {
let list = document.querySelector('ul'),
lastItem = document.querySelector('li:last-child');
list.removeChild(lastItem);
})
//delete a list item
removeToDo.addEventListener('click', () =>{
list.removeChild(li);
});
我知道这看起来很糟糕,但我只是想通过dom和寻找实现删除按钮功能的方法。有什么建议么?
I know it looks terrible, but I'm just looking to sharpen up my skills with the dom and find ways to achieve the delete button functionality. Any suggestions?
推荐答案
- 遍历所有按钮
- 添加事件侦听器
- 遍历列表容器并单击时删除相应的孩子
- Iterate over all the buttons
- Add event listener
- Traverse up to the list container and remove respective child on click
var deletes = document.querySelectorAll('.removeBtn')
// Iterate all nodes
deletes.forEach(btn => {
// Attach event listener. Note to preserve the button this-reference
// by using the non-shorthand function
btn.addEventListener('click', function() {
var li = this.parentNode
li.remove()
})
})
<ul>
<li>one<button class="removeBtn">Delete</button>
<li>two<button class="removeBtn">Delete</button>
</ul>
这篇关于使用DOM从列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!