javascript - 如果单击多个复选框中的一个复选框,如何触发功能
问题描述
我正在创建一个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>
推荐阅读
- python - Python 错误:“numpy.float64”对象没有属性“附加”
- php - Laravel - 更新数据库以适应数组
- android - 广播接收器未注册 onResume() 而 onPause() 注册
- excel - 使用 .Net core 2 和 EPPlus 下载 excel 文件
- javascript - Highcharts 复制图例标签
- javascript - 推荐一个优先考虑子级并且只允许一个渲染的 React 组件?
- java - java类测试器问题
- r - R 版本 3.5.1 安装错误:MCDM 和 OutrankingTools
- azure-data-explorer - 找不到数据源:com.microsoft.kusto.spark.datasource
- amazon-web-services - 使用 AWS 开发工具包生成 S3 对象的预签名 URL 是否需要任何费用?