我想从购物清单中删除商品,因此容易在html中添加的元素已成功删除。 但是,每当将一个新元素添加到列表中时,该元素就不会被删除,并表现出不希望的行为。
这是我的代码:
var del = document.getElementsByClassName("delete");
var ul = document.querySelector("ul");
var liElements = document.querySelectorAll("li");
//Creating delete button
function createDeleteButton() {
var delButton = document.createElement("button");
delButton.classList.add("delete");
delButton.appendChild(document.createTextNode("Delete"));
addEventListnerToNewlyAddedDeleteItem(document.getElementsByClassName("delete").length);
return delButton;
}
//Adding event listner to newly added delete button.
function addEventListnerToNewlyAddedDeleteItem(i) {
del = document.getElementsByClassName("delete");
del[i - 1].addEventListener("click", function(event) {
deleteListElement(i);
});
}
//Adding event listners to delete buttons specified in html file.
for (let i = 0; i < del.length; i++) {
del[i].addEventListener("click", function(event) {
deleteListElement(i);
});
}
//Function to remove list element
function deleteListElement(i) {
ul.removeChild(liElements[i]);
}
<ul>
<li>Birthday cake <button class="delete">Delete</button></li>
<li>Candles <button class="delete">Delete</button></li>
<li>Party hats <button class="delete">Delete</button></li>
<li>Baloons <button class="delete">Delete</button></li>
<li>Flowers <button class="delete">Delete</button></li>
</ul>
答案 0 :(得分:1)
处理动态添加的元素的标准方法是利用委托侦听器的概念,而不是将侦听器直接附加到可能动态创建的元素上。
这个想法依赖于使DOM冒泡的事件的概念,因此您可以将侦听器附加到最接近的祖先元素,而该元素不会动态更改。
您的代码示例:
const ul = document.querySelector('ul');
//Creating delete button
function createDeleteButton() {
const delButton = document.createElement("button");
delButton.classList.add("delete");
delButton.type = 'button';
delButton.appendChild(document.createTextNode("Delete"));
return delButton;
}
// event listener that removes list element when button is clicked
function deleteListElement(event) {
const {
target: btn
} = event; // get the target property from the event object as a local variable btn
if (btn.matches('button.delete')) {
btn.closest('ul').removeChild(btn.parentElement);
}
}
ul.addEventListener('click', deleteListElement);
document.getElementById('addListElement').addEventListener('click', function() {
const li = document.createElement('li');
li.textContent = 'new Listitem';
const btn = createDeleteButton();
li.appendChild(btn);
ul.appendChild(li);
})
<ul>
<li>Birthday cake <button class="delete" type="button">Delete</button></li>
<li>Candles <button class="delete" type="button">Delete</button></li>
<li>Party hats <button class="delete" type="button">Delete</button></li>
<li>Baloons <button class="delete" type="button">Delete</button></li>
<li>Flowers <button class="delete" type="button">Delete</button></li>
</ul>
<button id="addListElement" type="button">Add item</button>