{ -6ren">
gpt4 book ai didi

JavaScript 错误...单击按钮时未创建元素

转载 作者:行者123 更新时间:2023-12-01 02:44:17 25 4
gpt4 key购买 nike

我的代码如下所示,当单击“submitButton”时,它应该创建一个表,但它没有这样做。这是我的代码:

submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
document.newRow.appendChild(newInput);
document.newRow.appendChild(newInput2);
document.newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});

最佳答案

您无法通过 body 访问元素。您需要使用像 getElementById 等 DOM 函数。如果它是像循环中那样新创建的元素,您可以直接附加到它们,如下所示

var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");

var newInput = document.createElement("td");
var newInput2 = document.createElement("td");

newRow.appendChild(newInput);
newRow.appendChild(newInput2);
newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
<button id="submitButton" >button</button>

关于JavaScript 错误...单击按钮时未创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47354489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com