提示后在纯JS中保持复选框状态

时间:2018-11-04 03:40:45

标签: javascript dom

我有一个使用香草javascript编写的简单TODO应用。这是应用程序:

Step1

这时我遇到的问题/问题是:

当我单击“新建待办事项”按钮时,该复选框的现有选中状态将消失。

我不确定在提示窗口确定单击后如何保持复选框状态。请在下面找到源代码。

Step2

 const classNames = {
  TODO_ITEM: 'todo-container',
  TODO_CHECKBOX: 'todo-checkbox',
  TODO_TEXT: 'todo-text',
  TODO_DELETE: 'todo-delete',
}

const checkbox = document.createElement( "input" ); 
checkbox.type = "checkbox" 
checkbox.id = classNames.TODO_CHECKBOX 

const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')

function newTodo() {
  let newTodo = prompt("Please enter a todo item");
  if(newTodo){ 
    itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
    list.append(checkbox)
    list.innerHTML += "<li>" + newTodo 
  }

  let allCheckBoxes = document.querySelectorAll("input[id='todo-checkbox']");
  uncheckedCountSpan.innerHTML = allCheckBoxes.length
  console.log(allCheckBoxes.length)


  for(let i = 0; i < allCheckBoxes.length; i++){
  allCheckBoxes[i].onclick = function() {
    if ( this.checked ) {
      uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
    } 
    else {
      uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
    }
  };
  }
}

如果您有任何想法/方向,请告诉我。

谢谢。

1 个答案:

答案 0 :(得分:1)

您有两个问题:首先,您每次都附加相同的复选框。其次,您正在直接编辑innerHTML,这将迫使DOM重新呈现所有内容,还原输入的状态。这是我的处理方式:

const classNames = {
  TODO_ITEM: 'todo-container',
  TODO_CHECKBOX: 'todo-checkbox',
  TODO_TEXT: 'todo-text',
  TODO_DELETE: 'todo-delete',
}

const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')

function newTodo() {
  let newTodo = prompt("Please enter a todo item");
  if(!newTodo){
    return
  }
  itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
  uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
  const checkbox = document.createElement( "input" ); 
  checkbox.onclick = function() {
    if ( this.checked ) {
      uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
    } 
    else {
      uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
    }
  };
  checkbox.type = "checkbox" 
  checkbox.class = classNames.TODO_CHECKBOX 
  list.append(checkbox)
  const listItem = document.createElement("li")
  listItem.innerHTML = newTodo
  list.append(listItem)
}

请注意,我还将复选框的id替换为class-存在多个复选框,并且id应该是唯一的。