未为所有元素附加事件侦听器

问题描述

我在文档中附加了多个锚标记元素,但是只有第一个标记会触发我在Javascript文档底部功能

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>To-Do App</title>
  </head>
  <body>
    <div id="todos"></div>
    <script src="js/todo-app.js"></script>
  </body>
</html>

JavaScript:

let todo = [{title: "groceries"},{title: "laundry"},{title: "cook dinner"},];
const filters = {searchText: ''}
const renderTodos = function (todo,filters) {
  const filteredTodos = todo.filter(function (todo) {
    return todo.title.toLowerCase().includes(filters.searchText.toLowerCase());
  });
  filteredTodos.forEach(function (todo) {
    const todoElement = document.createElement('p');
    todoElement.setAttribute('class','paragraph');
    const todoDelete = document.createElement('a');
    todoDelete.setAttribute('href','#');
    todoDelete.textContent = "Delete Item";
    todoElement.textContent = todo.title;
    document.querySelector('#todos').appendChild(todoElement);
    document.querySelector('#todos').appendChild(todoDelete);
  });
}
renderTodos(todo,filters);
// The function I'm trying to trigger with the remaining anchor tags
document.querySelector('a').addEventListener('click',function () {console.log("item deleted");});

解决方法

为澄清我的评论中的错误,由于Array.from()返回NodeList而不是HTML集合,因此不必使用querySelectorAll来转换结果。

NodeList具有内置的forEach方法,因此无需在此示例中进行转换。但是,如果您想访问大多数其他数组方法,特别是mapfilter之类的循环方法,则必须这样做。

我相信此语法应适用于您的代码:

document.querySelectorAll('a').forEach(el => {
  el.addEventListener('click',() => console.log('item deleted'))
})
,

我发现了另一个StackOverflow问题,尝试与您做同样的事情。您可能要尝试这种方法:

How to select all tag and register onclick event?