如何向ul添加新li并删除较旧的li

时间:2019-05-01 11:43:27

标签: javascript

我需要接受用户输入并将其添加到list元素中,并在每次输入新列表项时删除其中一个较旧的列表项。

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>

但什么也没发生

2 个答案:

答案 0 :(得分:1)

此解决方案将删除最旧的待办事项,并将新的待办事项附加到列表的底部。我已经相应地修改了您的解决方案。

希望这会有所帮助。

(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>

答案 1 :(得分:0)

打开控制台(Chrome中为F12)。它告诉您问题出在哪里:Uncaught ReferenceError: getElementById is not defined。就像您代码中的其他任何地方一样,它应该是document.getElementById。第1行已修复,然后是一些代码优化建议(缓存DOM元素)和错误修正:

const addToDoBtn = document.getElementById('btn-addTodo'),
      ul = document.getElementById('todoList'),
      todoInput = document.getElementById('todoInput');
      
      

const changeAddToDoF = () => {

  const liNode = document.createElement('li'),
    textNode = document.createTextNode(todoInput.value);

  liNode.appendChild(textNode);
  ul.appendChild(liNode);
  
  todoInput.value= "";
}

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>