首页 > 解决方案 > 当创建一个元素,添加后的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");
}

有人可以给我一个解决这个问题的方法吗?感谢您的时间和回答!

标签: javascripthtmlonchangeappendchild

解决方案


更好的

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>


推荐阅读