Javascript .createElement & .appendChild Issue (Include for and if)



我是一个javascript新手。我需要一些帮助调试这段代码。我打算这样做的是基于列表中的值的数量,是创建一个3列宽的表来显示每个。顺便说一句,整个html格式都是用网格设置的。

错误是:未捕获的TypeError: Cannot read property of undefined (reading 'appendChild')

HTML (inside body):

<section id="db_gallery">
<table id="gallery_table"></table>
<script src="autogallery.js"></script>
</section>

JS in autogallery.js:

const gallery_table = document.getElementById("gallery_table");
const list = ["A", "B", "C", "D", "E", "F"];
for (let i of list) {
if (i % 3 === 0) {
let newRowItem = document.createElement("tr");
var idName = "newRowItem";
idName.concat(i);
newRowItem.setAttribute("id", idName);
gallery_table.appendChild(newRowItem);
}
let newColItem = document.createElement('th');
newColItem.textContent = i;
idName.appendChild(newColItem);
console.log(idName);
}

如果任何建议是简单易懂的,那将是一个很大的帮助。如果这意味着什么,我将最终链接到phpmyadmin数据库作为数组中的值。谢谢!

首先你应该用newRowItem.appendChild代替idName,因为newRowItem是你创建的元素。

其次,当使用for...of时,i是元素而不是索引,因此在您的情况下最好使用for

最后,你不应该在作用域外使用newRowItem,因为你在if语句中用let声明了它。

应该是正确的:

const gallery_table = document.getElementById("gallery_table");
let list = ["A", "B", "C", "D", "E", "F"];
var idName = "";
for (let i = 0; i < list.length; i++) {
if (i % 3 === 0) {
let newRowItem = document.createElement("tr");
idName = "newRowItem";
idName = idName.concat(list[i]);
newRowItem.setAttribute("id", idName);
gallery_table.appendChild(newRowItem);
let newColItem = document.createElement('th');
newColItem.textContent = list[i];
newRowItem.appendChild(newColItem);
}
}

Try

newRowItem.appendChild(newColItem)

不是

idName.appendChild(newColItem)

使用带有index的for循环对列表的索引进行模操作。

let newRowItem;
for (int i=0 ; i<list.length; i++) {
if (i % 3 === 0) {
newRowItem = document.createElement("tr");
var idName = "newRowItem";
idName.concat(i);
newRowItem.setAttribute("id", idName);
gallery_table.appendChild(newRowItem);
}
if(newRowItem){
let tag = i < 3 ? 'th' : 'td';
let newColItem = document.createElement(tag);
newColItem.textContent = list[i];
newRowItem.appendChild(newColItem);
console.log(newRowItem);
}
}`

最新更新