javascript - 当创建一个元素,添加后的onchange不是它的一部分
问题描述
我在表中添加了一些元素。有一个函数可以添加(tr 和 td)这些元素。函数内部有一部分:
for(var i = 0; i < 4; i++) {
cell = document.createElement("td");
row.appendChild(cell);
cellData = document.createElement("input");
cellData.type = "number";
cellData.min = "0"
cellData.max = "7";
cellData.value = "0";
cellData.onchange = "calculate()";
cell.appendChild(cellData);
}
这会放置 4 个带有输入字段的单元格。我的问题是,onchange 部分不起作用。我知道你可以直接将 onchange 函数添加到输入中。但在这种形式下它不起作用。我知道原因,当我在浏览器中检查它时,它跳过了 onchange 部分:
<td><input type="number" min="0" max="7"></td>
它只添加了这些。而且我没有从函数中得到我的消息:
function calculate() {
console.log("something");
}
有人可以给我一个解决这个问题的方法吗?感谢您的时间和回答!
解决方案
更好的
cellData.onchange = calculate;
甚至更好
cellData.addEventListener("change",calculate);
最好的,因为它只有一个事件监听器:
document.querySelector("#myTable tbody").addEventListener("input",calculate);
例子
const getNum = str => isNaN(str) || str.trim() === "" ? 0 : +str;
const tbody = document.querySelector("#myTable tbody");
const totalSpan = document.getElementById('total');
const calculate = fld => {
const total = [...tbody.querySelectorAll("[type=number]")].map(fld => getNum(fld.value)).reduce((a, b) => a + b)
totalSpan.textContent = total;
};
tbody.addEventListener("input", calculate);
const row = document.createElement("tr")
for (let i = 0; i < 4; i++) {
cell = document.createElement("td");
cellData = document.createElement("input");
cellData.type = "number";
cellData.min = "0"
cellData.max = "7";
cellData.value = "0";
cell.appendChild(cellData);
row.appendChild(cell);
}
tbody.appendChild(row);
<table id="myTable">
<tbody>
</tbody>
</table>
<span id="total"></span>
推荐阅读
- python - 复杂的乐透号码生成器 - Python
- format - 将标量从 sif 转换为 hrf
- powershell - 删除两个字符串之间的行powershell
- cmake - 在 Linux 环境中使用 cmake 安装时 HDF5 的未定义符号
- python - 谷歌云功能的内存分析器?
- javascript - 鼠标悬停上的 Js - 从两个 div 中查找匹配的文本
- azure - 如何使用 Visual Studio 2017 中的资源组项目自动部署 Function App 内容?
- c# - 我在哪里放置 GC.KeepAlive?
- c# - 安装在 Program Files 中时保存 App.Exe.Config
- javascript - 反应:在不将整个 DOM 元素作为道具传递的情况下更改模式的内容?