简体   繁体   中英

Button eventlistener not executing after other button clicked

https://codepen.io/ardiandaffa/pen/yLOZGGa

the code :

 function addProjectInit() { const modal = document.getElementById('modal'); const addProjectButton = document.getElementById('add-btn'); const span = document.getElementsByClassName('close')[0]; addProjectButton.onclick = () => { modal.style.display = "block"; } span.onclick = () => modal.style.display = "none"; window.onclick = () => { if (event.target == modal) { modal.style.display = "none"; } } }; function addProject() { const projectInputButton = document.getElementById('add-btn-modal'); const labelProject = document.getElementById('project-label'); const modal = document.getElementById('modal'); projectInputButton.onclick = () => { let title = document.getElementById('project-title-input').value; labelProject.innerHTML += createProject(title); modal.style.display = "none"; }; } function createProject (project) { return `<option value="Default">${project}</option>` } function addTodo() { const todoTitle = document.getElementById('todo'); const todoDate = document.getElementById('date'); const todoPriority = document.getElementById('todo-priority'); const todoButton = document.getElementById('todo-button'); const todoBox = document.getElementById('todolist-box'); todoButton.addEventListener("click", () => { let todoObject = todoObj(todoTitle.value, todoDate.value, todoPriority.options[todoPriority.selectedIndex].value); todoBox.innerHTML += createTodolist(todoObject); }); }; const todoObj = (title, dueDate, priority) => { return {title, dueDate, priority}; }; function createTodolist (todoObject) { return `<div class="todo-table"> <input type="checkbox" class="checkbox-todolist"> <a class="title-todolist">${todoObject.title}</a> <a class="date-todolist">${todoObject.dueDate}</a> <a class="priority-todolist">${todoObject.priority}</a> </div>` }; addProjectInit(); addProject(); addTodo();

So in the codepen above I could click the "ADD PROJECT" button. but, after adding todo and clicking the "ADD" button on the right side the "ADD PROJECT" button didn't work and the modal didn't show. Why is that?

You are appending html directly and this reset all registered events

 const todoBox = document.getElementById('todolist-box')
 todoBox.innerHTML += createTodolist(todoObject);

The add project button is inside todoBox so the onClick event reset whenever you change content of the dom

Create another div around and use this instead to append html

Like this https://codepen.io/stackoverflowuser/pen/xxVMMqy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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