javascript - 如何将新的 li 添加到 ul 并删除旧的

标签 javascript

我需要获取用户输入并将其附加到列表元素中,并使用每个新列表项输入删除旧列表项之一。

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/

相关文章:

javascript - 如何从 Angular ui bootstrap 模式传递表单数据以查看

javascript - React 中状态变量的顺序重要吗?

javascript - 使用 JavaScript 对数组中的每个数字进行平方 - 为什么只有第一个数字被平方并返回?

javascript - ServiceNow 平台中的服务器端验证

javascript - 如何从键/值 JSON 对象中提取键?

javascript - 如何使用 Javascript 获取客户端的 IP 地址

javascript - 输入时提交表格

javascript - .text函数不起作用

javascript - 我们在哪里可以找到 TextAngular 的 textarea 元素

javascript - Express.js HTTPS 未启动服务器