2 回答
TA贡献1877条经验 获得超6个赞
更好的
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>
TA贡献1828条经验 获得超6个赞
var row = window.document.createElement('tr');
document.getElementById("content").appendChild(row);
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);
}
function calculate() {
console.log("something");
}
<div id="content"> </div>
添加回答
举报