gpt4 book ai didi

javascript - 如果单击多个复选框中的一个复选框,如何触发函数

转载 作者:行者123 更新时间:2023-12-01 00:47:30 26 4
gpt4 key购买 nike

我正在创建一个 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;
}

没有发生任何事情,所以我不确定如何调试它

最佳答案

我想你需要这个

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>

关于javascript - 如果单击多个复选框中的一个复选框,如何触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com