首页 > 解决方案 > 如果单击多个复选框中的一个复选框,如何触发功能

问题描述

我正在创建一个todo应用程序,当检查任何一个复选框时,我需要触发一个函数(计算检查的复选框数量)。

如果单击复选框,我将无法发生 onlick 事件。我已经设法用提交按钮做到了,但没有用复选框本身

//the html
<div class="flow-right controls">
        <span>Item count: <span id="item-count">0</span></span>
        <span>Unchecked count: <span id="unchecked-count">0</span></span>
      </div>
      <button class="button center" onClick="newTodo()">New TODO</button>
      <ul id="todo-list" class="todo-list"></ul>
    </div>

// the function above this one creates the checkbox and appends it to the list in the HTML
const box = document.createElement('INPUT');
      box.type = "checkbox";
      box.name = "countme";
      box.id = "checkme"
      li.appendChild(box);

// this is the code I have created to trigger a function unchecked which returns the count of unchecked checkboxes.

let getcheck = document.getElementsByName("countme");
for (let i = 0; i < getcheck.length; i++) {
   getcheck[i].onClick = unchecked;
 }

什么都没有发生,所以我不确定如何调试它

标签: javascriptcheckbox

解决方案


我想你需要这个

function newTodo() {
  let ulElement = document.getElementById('todo-list');
  let todoElement = document.createElement('li');
  const box = document.createElement('INPUT');
      box.type = "checkbox";
      box.name = "countme";
      box.id = "checkme";
      box.value = 0;
      todoElement.appendChild(box);
  const span = document.createElement('span').TEXT_NODE = 'To do task';
  todoElement.append(span);
  ulElement.append(todoElement);
  let unCheckELement = document.getElementById('unchecked-count');
  unCheckELement.textContent = parseInt(unCheckELement.textContent) + 1;
  box.onchange = onCheckboxCheck;
}
function onCheckboxCheck(element) {
  let count = parseInt(document.getElementById('item-count').textContent);
  count += element.srcElement.checked ? 1 : -1;
  let allElements = document.querySelectorAll('#todo-list li').length;
  document.getElementById('item-count').textContent = count;
  document.getElementById('unchecked-count').textContent = allElements - count;

}
<div class="flow-right controls">
    <span>Item count: <span id="item-count">0</span></span>
    <span>Unchecked count: <span id="unchecked-count">0</span></span>
  </div>
    <button class="button center" onClick="newTodo()">New TODO</button>
    <ul id="todo-list" class="todo-list"></ul>


推荐阅读