我有一個類似的類結構,它對我不起作用,我已經嘗試了幾件事,但無法解決問題。如您所見,建構式被正確執行,并且在最后一個建構式中執行了方法。但是,當我創建 HTML 內容時,它不會繪制它。為什么以及如何解決這個問題?
class AutoComplete{
constructor(){
console.log("constructor autocomplete")
this.table = new Table();
}
}
class Table{
constructor(){
console.log("constructor table")
this.arr = []
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => {
data.map(d => this.arr.push(d))
});
this.fill();
}
fill = () => {
console.log("fill");
const content = document.querySelector("#content");
// doesn't work
this.arr.forEach( ct => {
const div = document.createElement("div");
div.innerText = ct.body;
content.appendChild(div);
//content.innerHTML = div;
});
}
}
let autoc = new AutoComplete();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="content"></div>
</body>
</html>
uj5u.com熱心網友回復:
發生這種情況是因為您需要this.fill()在.then()回呼函式中呼叫。除此以外。this.fill在從 API 取回資料之前呼叫。
演示:
class AutoComplete{
constructor(){
console.log("constructor autocomplete")
this.table = new Table();
}
}
class Table{
constructor(){
console.log("constructor table")
this.arr = []
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => {
data.map(d => this.arr.push(d));
this.fill();
})
// this.fill()
}
fill = () => {
console.log("fill");
const content = document.querySelector("#content");
// doesn't work
this.arr.forEach(ct => {
const div = document.createElement("div");
div.innerText = ct.body;
content.appendChild(div);
//content.innerHTML = div;
});
}
}
let autoc = new AutoComplete();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="content"></div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319121.html
標籤:javascript html 拿来
上一篇:延遲加載:DIVonClick,隱藏元素,添加iFrame。無法弄清楚回圈程序
下一篇:平滑下拉選單
