简体   繁体   English

为什么 addEventListener 没有在点击时触发该方法?

[英]Why is the addEventListener not triggering the method on click?

I am creating a simple To-Do list.我正在创建一个简单的待办事项列表。 The addEventListener() is supposed to trigger the method addToDo and create a new div inside which the lists are appended. addEventListener() 应该触发方法addToDo并创建一个新的 div,在其中附加列表。

But the method is not triggered and the div isn't added.但是没有触发该方法,也没有添加 div。 Tried the solutions from the question and other questions but they don't seem to fix the problem.尝试了问题和其他问题的解决方案,但它们似乎没有解决问题。

 const todoInput = document.querySelector('.todo-input'); const todoButton = document.querySelector('.todo-button'); const todoList = document.querySelector('.todo-list'); //EventListeners todoButton.addEventListener('click', addToDo, false); //Functions function addToDo(event) { event.preventDefault(); //ToDo Div const todoDiv = document.createElement('div'); todoDiv.classList.add('todo'); //Create <li> const newToDo = document.createElement('li'); newToDo.innerText = 'hey'; newToDo.classList.add('todo-item'); todoDiv.appendChild(newToDo); }
 <form> <input type="text" class="todo-input"> <button class="todo-button" type="submit"> <i class="fas fa-plus-square"></i> </button> </form> <div class="todo-container"> <ul class="todo-list"> </ul> </div>

It is triggered.它被触发。 You just can't see anything changing because newly created todoDiv is not being mounted anywhere.你只是看不到任何变化,因为新创建的todoDiv没有安装在任何地方。

Instead of appending to todoDiv try appending to todoList .而不是附加到todoDiv尝试附加到todoList

function addToDo(event) {
    event.preventDefault();

    //Create <li>
    const newToDo = document.createElement('li');
    newToDo.innerText = 'hey';
    newToDo.classList.add('todo-item');
    todoList.appendChild(newToDo);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM