我正在尝试将我的代码输出到html文件的api对象 .
const container = document.createElement('div');
container.setAttribute('class', 'container');
obj = fetch('https://apis.is/concerts')
.then(function(response) {
return response.json();
})
.then(function(data) {
return obj = data;
})
.then(() => idk())
function idk() {
let count = 0;
for(key in obj.results) {
count++;
};
console.log(count);
for(let i = 0; i < count; i++) {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = obj.results[i].eventDateName;
const p = document.createElement('p');
p.textContent = obj.results[i].dateOfShow;
container.appendChild(card);
card.appendChild(h1);
card.appendChild(p);
};
};
我一直在尝试使用DOM为html文件创建元素,但它就像是忽略了一些代码 .
1 回答
如果要渲染所有正在创建的DOM,则必须以某种方式将其添加到浏览器正在显示的DOM树中 . 简单的方法是将它添加到body节点 .
document.querySelector('body').appendChild(container);
完成数据处理后 .但我建议稍微重构一下你的代码 . 例如,在此步骤中,您将结果分配给原始对象,您将使用结果保存承诺 . 这也是一个非常快速的全局对象,你最终可能会遇到竞争条件 .
.then(function(data) { return obj = data; })
此外,idk()函数耦合到非常具体的变量obj,这将使它很难测试 .