簡體   English   中英

如何使用 JavaScript 讓這個 div 再次顯示

[英]How do I get this div to show again using JavaScript

我制作了一個 TODO 應用程序並添加了一個計數器來記錄列表中的項目。 如果計數器達到零,我已將其設置為重新顯示消息“您當前沒有任務。 使用上面的輸入字段開始添加。

if(count === 0){
  noTasksText.classList.remove('d-none');
}

在控制台中,我打印出 div 並且在類列表中不再有d-none這是我想要的,但是在實際的 DOM 中它確實如此。

這是一個完整的例子 - https://codepen.io/tomdurkin/pen/LYdpXKJ?editors=1111

我真的無法解決這個問題。 當計數器變為零時,我似乎無法與該 div 交互,但是我可以讓控制台日志等在預期時顯示。

任何幫助,將不勝感激!

 const mainInput = document.querySelector('#main-input'); const todoContainer = document.querySelector('#todo-container'); const errorText = document.querySelector('#js-error'); const noTasksText = document.querySelector('.js-no-tasks') let tasks = []; let count = 0; // focus input on load window.onload = () => { mainInput.focus(); const storedTasks = JSON.parse(localStorage.getItem('tasks')); if (storedTasks != null && storedTasks.length > 0) { // set count to number of pre-existing items count = storedTasks.length // hide the 'no tasks' text noTasksText.classList.add('d-none'); // overwrite tasks array with stored tasks tasks = storedTasks; tasks.forEach(task => { // Build the markup const markup = ` <div class="js-single-task single-task border-bottom pt-2 pb-2"> <div class="row"> <div class="col d-flex align-items-center js-single-task-name"> <h5 class="mb-0" data-title="${task}">${task}</h5> </div> <div class="col d-flex justify-content-end"> <button class="js-remove-task d-block btn btn-danger">Remove Item</button> </div> </div> </div>`; // Append it to the container todoContainer.innerHTML += markup; }); } else { if (noTasksText.classList.contains('d-none')) { noTasksText.classList.remove('d-none'); } } }; // event listener for 'enter on input' mainInput.addEventListener("keydown", e => { // if error is showing, hide it! if (!errorText.classList.contains('d-none')) { errorText.classList.add('d-none'); } if (e.key === "Enter") { // Get the value of the input let inputValue = mainInput.value; if (inputValue) { // Build the markup const markup = ` <div class="js-single-task border-bottom pt-2 pb-2"> <div class="row"> <div class="col d-flex align-items-center js-single-task-name"> <h5 class="mb-0" data-title="${inputValue}">${inputValue}</h5> </div> <div class="col d-flex justify-content-end"> <button class="js-remove-task d-block btn btn-danger">Remove Item</button> </div> </div> </div>`; // hide 'no tasks' text noTasksText.classList.add('d-none'); // Append it to the container todoContainer.innerHTML += markup; // Push value to 'tasks' array tasks.push(inputValue); // Put in localStorage textTasks = JSON.stringify(tasks); localStorage.setItem("tasks", textTasks); // Reset the value of the input field mainInput.value = ''; // add 1 to the count count++ } else { // Some very basic validation errorText.classList.remove('d-none'); } } }); // remove task todoContainer.addEventListener('click', (e) => { // Find the button in the row that needs removing (bubbling) const buttonIsDelete = e.target.classList.contains('js-remove-task'); if (buttonIsDelete) { // Remove the HTML from the screen e.target.closest('.js-single-task').remove(); // Grab the name of the single task let taskName = e.target.closest('.js-single-task').querySelector('.js-single-task-name h5').getAttribute('data-title'); // filter out the selected word tasks = tasks.filter(item => item != taskName); textTasks = JSON.stringify(tasks); localStorage.setItem("tasks", textTasks); // update counter count-- // check if counter is zero and re-show 'no tasks' text if true if (count === 0) { noTasksText.classList.remove('d-none'); console.log(noTasksText); } } });
 body { background: #e1e1e1; }
 <div class="container"> <div class="row d-flex justify-content-center mt-5"> <div class="col-10 col-lg-6"> <div class="card p-3"> <h2>To dos</h2> <p> Use this app to keep a list of things you need to do </p> <input class="form-control" id="main-input" type="text" placeholder="Type your todo and hit enter..." class="w-100" /> <small id="js-error" class="text-danger d-none"> Please type a value and press enter </small> <hr /> <h4 class="mb-5">Your 'To dos'</h4> <div id="todo-container"> <!-- todos append in here --> <div class="js-no-tasks"> <small class="d-block w-100 text-center mb-3"> <i> You currently have no tasks. Use the input field above to start adding </i> </small> </div> </div> </div> <!-- /card --> </div> </div> </div>

在使用+= innerHTML設置innerHTML時,節點noTasksText會丟失,因為瀏覽器會處理整個新設置的innerHTML並創建新對象。 您可以在此之后再次檢索noTasksText ,或者使用todoContainer.appendChild附加節點。 我叉了你的筆並用后一種解決方案解決了它。

https://codepen.io/aghosey/pen/wvmGwWd

您可以執行以下操作,它將起作用(這里 innerHTML 正在更改 DOM,因此我添加了一個額外的函數來在由於 innerHTML 而更改 DOM 后重新計算元素):

 var mainInput = document.querySelector("#main-input"); var todoContainer = document.querySelector("#todo-container"); var errorText = document.querySelector("#js-error"); var noTasksText = document.querySelector(".js-no-tasks"); let tasks = []; let count = 0; function getAllElements() { mainInput = document.querySelector("#main-input"); todoContainer = document.querySelector("#todo-container"); errorText = document.querySelector("#js-error"); noTasksText = document.querySelector(".js-no-tasks"); } // focus input on load window.onload = () => { mainInput.focus(); var storedTasks = JSON.parse(localStorage.getItem("tasks")); if (storedTasks != null && storedTasks.length > 0) { // set count to number of pre-existing items count = storedTasks.length; // hide the 'no tasks' text noTasksText.classList.add("d-none"); // overwrite tasks array with stored tasks tasks = storedTasks; tasks.forEach((task) => { // Build the markup const markup = ` <div class="js-single-task single-task border-bottom pt-2 pb-2"> <div class="row"> <div class="col d-flex align-items-center js-single-task-name"> <h5 class="mb-0" data-title="${task}">${task}</h5> </div> <div class="col d-flex justify-content-end"> <button class="js-remove-task d-block btn btn-danger">Remove Item</button> </div> </div> </div>`; // Append it to the container todoContainer.innerHTML += markup; getAllElements(); }); } else { if (noTasksText.classList.contains("d-none")) { noTasksText.classList.remove("d-none"); } } }; // event listener for 'enter on input' mainInput.addEventListener("keydown", (e) => { // if error is showing, hide it! if (!errorText.classList.contains("d-none")) { errorText.classList.add("d-none"); } if (e.key === "Enter") { // Get the value of the input let inputValue = mainInput.value; if (inputValue) { // Build the markup const markup = ` <div class="js-single-task border-bottom pt-2 pb-2"> <div class="row"> <div class="col d-flex align-items-center js-single-task-name"> <h5 class="mb-0" data-title="${inputValue}">${inputValue}</h5> </div> <div class="col d-flex justify-content-end"> <button class="js-remove-task d-block btn btn-danger">Remove Item</button> </div> </div> </div>`; // hide 'no tasks' text noTasksText.classList.add("d-none"); // Append it to the container todoContainer.innerHTML += markup; getAllElements(); // Push value to 'tasks' array tasks.push(inputValue); // Put in localStorage textTasks = JSON.stringify(tasks); localStorage.setItem("tasks", textTasks); // Reset the value of the input field mainInput.value = ""; // add 1 to the count count++; } else { // Some very basic validation errorText.classList.remove("d-none"); } } }); // remove task todoContainer.addEventListener("click", (e) => { // Find the button in the row that needs removing (bubbling) const buttonIsDelete = e.target.classList.contains("js-remove-task"); if (buttonIsDelete) { // Remove the HTML from the screen e.target.closest(".js-single-task").remove(); // Grab the name of the single task let taskName = e.target .closest(".js-single-task") .querySelector(".js-single-task-name h5") .getAttribute("data-title"); // filter out the selected word tasks = tasks.filter((item) => item != taskName); textTasks = JSON.stringify(tasks); localStorage.setItem("tasks", textTasks); // update counter count--; // check if counter is zero and re-show 'no tasks' text if true if (count === 0) { noTasksText.classList.remove("d-none"); console.log(noTasksText); } } });
 body { background: #e1e1e1; }
 <div class="container"> <div class="row d-flex justify-content-center mt-5"> <div class="col-10 col-lg-6"> <div class="card p-3"> <h2>To dos</h2> <p> Use this app to keep a list of things you need to do </p> <input class="form-control" id="main-input" type="text" placeholder="Type your todo and hit enter..." class="w-100" /> <small id="js-error" class="text-danger d-none"> Please type a value and press enter </small> <hr /> <h4 class="mb-5">Your 'To dos'</h4> <div id="todo-container"> <!-- todos append in here --> <div class="js-no-tasks"> <small class="d-block w-100 text-center mb-3"> <i> You currently have no tasks. Use the input field above to start adding </i> </small> </div> </div> </div> <!-- /card --> </div> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM