我有一种方法可以在选中复选框时从列表中删除项目。第一项被删除正常,但当我想删除后续项目时,我收到此错误:
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
但根据我的代码,我觉得我做的是正确的事情。你能告诉我遗失的是什么吗?
HTML:
<ul class="category-list">
<li class="product-item">
<article class="product-item__wrapper">
<h1>
<label for="product_item_1">
<input type="checkbox" name="product_item_1" id="product_item_1">
Product Item
</label>
</h1>
</article>
</li>
<li class="product-item">
<article class="product-item__wrapper">
<h1>
<label for="product_item_2">
<input type="checkbox" name="product_item_2" id="product_item_2">
Product Item
</label>
</h1>
</article>
</li>
<li class="product-item">
<article class="product-item__wrapper">
<h1>
<label for="product_item_3">
<input type="checkbox" name="product_item_3" id="product_item_3">
Product Item
</label>
</h1>
</article>
</li>
<li class="product-item">
<article class="product-item__wrapper">
<h1>
<label for="product_item_4">
<input type="checkbox" name="product_item_4" id="product_item_4">
Product Item
</label>
</h1>
</article>
</li>
</ul>
JS:
import utils from 'utils';
class CategoryList {
constructor() {
this._categoryLists;
}
init(component) {
this._categoryLists = document.querySelector(component);
}
_deleteItem() {
let categoryList;
let productItems;
let productItem;
let productItemInnerWrapper;
let checkboxes;
let checkbox;
for (categoryList of this._categoryLists) {
checkboxes = categoryList.querySelectorAll('.product-item__checkbox');
for (checkbox of checkboxes) {
if (checkbox.checked) {
productItem = utils.findParent(
checkbox,
'product-item'
);
productItemInnerWrapper =
productItem.querySelector('.product-item__wrapper');
productItemInnerWrapper.classList.add('product-item__wrapper--animate');
productItem.classList.add('product-item__item--animate');
setTimeout(() => {
categoryList.removeChild(productItem); // --> This produces an error. I don't know why
}, 500);
}
}
}
}
}
export default CategoryList;
答案 0 :(得分:0)
每次都应该有效的简单解决方案是直接从要删除的元素中获取parentNode
:
productItem.parentNode.removeChild(productItem);