我正在尝试制作一个单页网络应用程序,并且我有不同的选项卡,例如未批准的选项卡。当我单击此选项卡时,我会使用 js 阻止默认使用操作,然后我会获取页面的容器元素
let container = document.getElementById('container');
然后我在容器中插入一个表格
container.innerHTML = `
<table id="table" class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody id="tablebody">
</tbody>
</table>
`;
完成后,我使用 ajax 获取一些数据,然后使用 js 插入到表体中。
try {
http.get('../includes/unapproved.inc.php')
.then(res => {
//check if the response if ok
console.log(res);
let rows = '';
for (let i in res) {
rows += `
<tr>
<td>${res[i].user_user_id} <td>
<tr>
`
}
tablebody.innerHTML = rows;
console.log(table);
});
} catch (error) {
console.log(error);
}
但是当我尝试插入数据时出现此错误
pages.js:51 Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
at pages.js:51
我不明白为什么会收到此错误,但我已经将表插入到 DOM 中。
下面是完整代码
import { FETCH } from "./fetch.js";
export class PAGES {
constructor() {
this.unapproved = document.getElementById('unapproved');
}
events() {
this.unapproved.addEventListener('click', (e) => {
e.preventDefault();
this.unapprovedPage();
})
}
unapprovedPage() {
let container = document.getElementById('container');
let table = document.getElementById('table');
let tablebody = document.getElementById('tablebody');
container.innerHTML = `
<table id="table" class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody id="tablebody">
</tbody>
</table>
`;
const http = new FETCH;
try {
http.get('../includes/unapproved.inc.php')
.then(res => {
//check if the response if ok
console.log(res);
let rows = '';
for (let i in res) {
rows += `
<tr>
<td>${res[i].user_user_id} <td>
<tr>
`
}
tablebody.innerHTML = rows;
console.log(table);
});
} catch (error) {
console.log(error);
}
}
}
最佳答案
您正在选择文档中之前的 #tablebody
元素。因此结果将始终为 null
。
首先添加容器元素的innerHTML
内容。
container.innerHTML = `
<table id="table" class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody id="tablebody">
</tbody>
</table>
`;
然后使用querySelector
从容器中选择元素。
let tablebody = container.querySelector('#tablebody');
此外,在附加动态内容时请防止使用 ID,而应使用类。当页面上存在多个具有相同 ID 的元素时,您的页面将无法按预期工作。
关于javascript - 如何使用 Js 在 HTML BODY 中插入一个元素,然后使用 Js 选择相同的元素,然后向其中附加更多数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59487605/