创建 <input> 元素时,添加后的 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");

}

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


湖上湖
浏览 113回答 2
2回答

慕哥9229398

更好的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 => {&nbsp; const total = [...tbody.querySelectorAll("[type=number]")].map(fld => getNum(fld.value)).reduce((a, b) => a + b)&nbsp; totalSpan.textContent = total;};tbody.addEventListener("input", calculate);const row = document.createElement("tr")for (let i = 0; i < 4; i++) {&nbsp; cell = document.createElement("td");&nbsp; cellData = document.createElement("input");&nbsp; cellData.type = "number";&nbsp; cellData.min = "0"&nbsp; cellData.max = "7";&nbsp; cellData.value = "0";&nbsp; cell.appendChild(cellData);&nbsp; row.appendChild(cell);}tbody.appendChild(row);<table id="myTable">&nbsp; <tbody>&nbsp; </tbody></table><span id="total"></span>

30秒到达战场

var row = window.document.createElement('tr');document.getElementById("content").appendChild(row);for(var i = 0; i < 4; i++) {&nbsp; &nbsp; cell = document.createElement("td");&nbsp; &nbsp; row.appendChild(cell);&nbsp; &nbsp; cellData = document.createElement("input");&nbsp; &nbsp; cellData.type = "number";&nbsp; &nbsp; cellData.min = "0"&nbsp; &nbsp; cellData.max = "7";&nbsp; &nbsp; cellData.value = "0";&nbsp; &nbsp; cellData.onchange = calculate ;&nbsp; &nbsp; cell.appendChild(cellData);&nbsp; &nbsp;&nbsp;}function calculate() {&nbsp; &nbsp; console.log("something");}<div id="content"> </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript