所以我有一个名为get_offices()
的方法,它正确地输出数据,如下所示:x1c 0d1x
下面是函数代码:
function get_offices(page_id = 1) {
make_request(`https://sample-api.fleishmanhillard.com/offices/?page=${page_id}`)
.then(response => {
if (response.status >= 200 && response.status < 400) {
return response.json();
} else {
throw 'There has been an error in the response status.';
}
}).then((json_data) => {
const data = json_data.data.offices;
const office = document.getElementById('office_result');
data.forEach(entry => {
const element = document.createElement('div');
element.classList.add('column', 'tile', 'is-3', 'has-text-left');
element.innerHTML = `
<article class='tile is-child box' style="height: 300px;">
<p class="title">` + entry.location + `</p>
<p><span class="has-text-weight-semibold">ID:</span> ${entry.id}</p>
<p><span class="has-text-weight-semibold">Brand:</span> ${entry.brand}</p>
<p><span class="has-text-weight-semibold">Location:</span> ${entry.location}</p>
<p><span class="has-text-weight-semibold">City:</span> ${entry.city}</p>
</article>`;
office.appendChild(element);
});
})
}
字符串
这工作得很好,但是现在如果我想利用.forEach中的代码并创建一个函数,如下所示:
function render_office(entry) {
const office = document.getElementById('office_result');
const element = document.createElement('div');
office.innerHTML = '';
element.classList.add('column', 'tile', 'is-3', 'has-text-left');
element.innerHTML = `
<article class='tile is-child box' style="height: 300px;">
<p class="title">` + entry.location + `</p>
<p><span class="has-text-weight-semibold">ID:</span> ${entry.id}</p>
<p><span class="has-text-weight-semibold">Brand:</span> ${entry.brand}</p>
<p><span class="has-text-weight-semibold">Location:</span> ${entry.location}</p>
<p><span class="has-text-weight-semibold">City:</span> ${entry.city}</p>
</article>`;
office.appendChild(element);
}
型
然后调用函数,如下所示:
function get_offices(page_id = 1) {
make_request(`https://sample-api.fleishmanhillard.com/offices/?page=${page_id}`)
.then(response => {
if (response.status >= 200 && response.status < 400) {
return response.json();
} else {
throw 'There has been an error in the response status.';
}
}).then((json_data) => {
const data = json_data.data.offices;
const office = document.getElementById('office_result');
office.innerHTML = '';
data.forEach(entry => {
render_office(entry);
});
})
}
型
这只是输出一个结果,我不知道为什么它没有多次执行函数并循环,如下所示:
如果有人能告诉我为什么函数的行为与HTML代码在块中时不一样,所有的帮助都将不胜感激!
2条答案
按热度按时间cbjzeqam1#
不用每次都更新DOM会快得多,而且当你改变渲染时,你也不会有这样的错别字的风险
字符串
和使用
型
jtjikinw2#
你有一个
字符串
在
render_office()
中,所以每次迭代在添加新内容之前都会清理div。把那条线去掉你就可以走了。