我需要获取用户输入并将其附加到列表元素中,并使用每个新列表项输入删除旧列表项之一。
const addToDoBtn = getElementById('btn-addTodo');
const changeAddToDoF = () => {
var ul = document.getElementById('todoList').removeAttribute;
var todoInput = document.getElementById('todoInput').value,
listNode = document.getElementById('todoList'),
liNode = document.createElement('LI'),
textNode = document.createTextNode(todoInput);
liNode.appendChild(textNode);
listNode.appendChild(liNode);
}
addToDoBtn.addEventListener("click", () => changeAddToDoF());
<div>
<h3>Todos:</h3>
<ul id="todoList">
<li>Hack the future</li>
<li>Learn javascript</li>
<li>Take over the world</li>
</ul>
<input type="text" id="todoInput" />
<button id="btn-addTodo">Add todo</button>
</div>
但是什么也没发生
最佳答案
此解决方案删除最旧的待办事项并将新的待办事项附加到列表底部。我已相应地修改了您的解决方案。
希望这对您有所帮助。
(function() {
const addToDoBtn = document.getElementById('btn-addTodo');
const changeAddToDoF = () => {
var todoInput = document.getElementById('todoInput').value,
listNode = document.getElementById('todoList'),
liNode = document.createElement('li'),
textNode = document.createTextNode(todoInput);
liNode.appendChild(textNode);
//Removes old item from the list
listNode.removeChild(listNode.getElementsByTagName('li')[0]);
// appends the new item to the list
listNode.appendChild(liNode);
}
addToDoBtn.addEventListener("click", () => changeAddToDoF());
})();
<div>
<h3>Todos:</h3>
<ul id="todoList">
<li>Hack the future</li>
<li>Learn javascript</li>
<li>Take over the world</li>
</ul>
<input type="text" id="todoInput" />
<button id="btn-addTodo">Add todo</button>
</div>
关于javascript - 如何将新的 li 添加到 ul 并删除旧的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935731/