Как я могу считать элементы в списке в Vanilla Javascript? - PullRequest
0 голосов
/ 15 апреля 2019

Я хочу создать счетчик для моего списка дел.Он показывает количество всех предметов.Но он не обновляется, когда я добавляю элемент.Он остается на уровне 3.

Это мой код Javascript;

var count = document.getElementById("list").childElementCount;
document.getElementById("title").innerHTML = ("You have " + count + " to-dos.");

// add item 
function todoList() {
    var item = document.getElementById("todoInput").value
    var text = document.createTextNode(item)
    var newItem = document.createElement("li")
    var check = document.createElement("span")
    check.className = "circle"
    newItem.appendChild(check)
    newItem.appendChild(text)
    document.getElementById("list").appendChild(newItem)

    // clear input value 
    document.getElementById("todoInput").value = "";
}

document.getElementById("add").addEventListener('click', todoList, null);

Это мой HTML-код;

<div class="progress">
    <div id="title"></div>
</div>

<ul id="list">
    <li><span class="circle"></span>Buid a task app</li>
    <li><span class="circle"></span>Do exercise</li>
    <li><span class="circle"></span>Buy headphones</li>
</ul>

Ответы [ 2 ]

1 голос
/ 15 апреля 2019

СУХОЙ метод заключается в создании функции, которую вы можете вызывать, чтобы вам не нужно было дублировать какой-либо код.

// Cache your elements
const title = document.getElementById('title');
const list = document.getElementById('list');
const input = document.getElementById('todoInput');
const add = document.getElementById('add')

// A new updateCount function
function updateCount() {
  const count = list.childElementCount;

  // Using a template literal is tidier than string concatenation
  // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals
  title.innerHTML = `You have ${count} to-dos.`;
}

function todoList() {
  const item = input.value
  const text = document.createTextNode(item)
  const newItem = document.createElement('li')
  const check = document.createElement('span')
  check.className = 'circle'
  newItem.appendChild(check)
  newItem.appendChild(text)
  list.appendChild(newItem)
  input.value = '';

  // Call your updateCount function after a new item
  // has been added
  updateCount();
}

// Call updateCount initially when the page loads
updateCount();
add.addEventListener('click', todoList, false);
<div class="progress">
  <div id="title"></div>
</div>

<ul id="list">
  <li><span class="circle"></span>Build a task app</li>
  <li><span class="circle"></span>Do exercise</li>
  <li><span class="circle"></span>Buy headphones</li>
</ul>

<input id="todoInput" />
<button id="add">Add</button>
1 голос
/ 15 апреля 2019

Просто повторите подсчет детей внутри функции todoList()

 var count = document.getElementById("list").childElementCount;
  document.getElementById("title").innerHTML = ("You have " + count + " to-dos.");

// add item 
function todoList() {
  var item = document.getElementById("todoInput").value
  var text = document.createTextNode(item)
  var newItem = document.createElement("li")
  var check = document.createElement("span")
  check.className = "circle"
  newItem.appendChild(check)
  newItem.appendChild(text)
  document.getElementById("list").appendChild(newItem)


  count = document.getElementById("list").childElementCount;
  document.getElementById("title").innerHTML = ("You have " + count + " to-dos.");

  // clear input value 
  document.getElementById("todoInput").value = "";

}

document.getElementById("add").addEventListener('click', todoList, null);

или вы можете прочитать о геттеров и сеттеров в javascript

...