在JavaScript待办事项应用程式中建立计数器

时间:2018-08-22 17:46:41

标签: javascript events

我制作了一个小小的javascript待办应用程序,以使其语言变得更好。我正在尝试创建一个计数器,该计数器在每次将任务添加到有序列表中时都会增加,但是它不起作用。这是我的代码:

var button = document.getElementById('add-button');

button.addEventListener('click', function() {
  var item = document.getElementById('input').value;
  var text = document.createTextNode(item);
  var newItem = document.createElement('li');
  newItem.appendChild(text);
  document.getElementById('todoList').appendChild(newItem);
  var count = 0;
  count++;
  document.getElementById('counter').innerHTML = count;


  var removeTask = document.createElement('img');
  removeTask.setAttribute('src', '/images/trash.jpg');
  removeTask.setAttribute('id', 'trash');
  removeTask.addEventListener('click', function() {
    newItem.parentNode.removeChild(newItem);
  });
  newItem.appendChild(removeTask);

});
<div class="header">
  <form>
    <h2>Todo App</h2>
    <p>Add a new todo</p>
    <input type="text" id="input" placeholder="Enter an activity......">
    <button type="button" id="add-button">Add Task</button>
  </form>
</div>
<ol id="todoList">
  <h1>Things to do:</h1>
  <div id="counter">0</div>
</ol>

现在,单击一次它会增加到1,但到此结束。我尝试制作一个for循环,该循环一直循环到newItem的长度,但这根本不起作用。每次添加项目时如何使它递增?

1 个答案:

答案 0 :(得分:1)

您需要在事件监听器的范围之外定义count,否则对于添加的每个项目,您始终将0递增1(0 + 1始终为1)。将声明放在侦听器之外,并增加该值:

var button = document.getElementById('add-button');
var count = 0;


button.addEventListener('click', function() {
  var item = document.getElementById('input').value;
  var text = document.createTextNode(item);
  var newItem = document.createElement('li');
  newItem.appendChild(text);
  document.getElementById('todoList').appendChild(newItem);
  count++;
  document.getElementById('counter').innerHTML = count;


  var removeTask = document.createElement('img');
  removeTask.setAttribute('src', '/images/trash.jpg');
  removeTask.setAttribute('id', 'trash');
  removeTask.addEventListener('click', function() {
    newItem.parentNode.removeChild(newItem);
  });
  newItem.appendChild(removeTask);

});
<div class="header">
  <form>
    <h2>Todo App</h2>
    <p>Add a new todo</p>
    <input type="text" id="input" placeholder="Enter an activity......">
    <button type="button" id="add-button">Add Task</button>
  </form>
</div>
<ol id="todoList">
  <h1>Things to do:</h1>
  <div id="counter">0</div>
</ol>