简体   繁体   English

在div中显示所有结果

[英]Display all results in div

I have a foreach loop that goes through all possible results of an API query 我有一个遍历API查询所有可能结果的foreach循环

json.results.forEach(function(result) {
     console.log(result.original_title);
     document.getElementById("possibleResults").innerText = result.original_title;
}, this);

The console.log outputs all the elements correctly, however as expected, when I write to the possible results div, it only displays the last result. console.log正确输出所有元素,但是按预期,当我写入可能的结果 div时,它仅显示最后一个结果。

How can I write my results to a div sequentially, so they are not overwritten, preferably without CSS? 如何将结果顺序写入div,这样就不会被覆盖,最好不要使用CSS?

Change document.getElementById("possibleResults").innerText = result.original_title; 更改document.getElementById("possibleResults").innerText = result.original_title; to document.getElementById("possibleResults").innerText += result.original_title; document.getElementById("possibleResults").innerText += result.original_title; The first option replaces the current content of the div, that's why you only see the last result. 第一个选项替换了div的当前内容,这就是为什么您仅看到最后一个结果的原因。 The second one appends it to the end, keeping every result. 第二个附加到末尾,保留每个结果。

add all content after it is written in a variable. 将所有内容写入变量后添加。

var content;
json.results.forEach(function(result) {
       console.log(result.original_title);
       content += result.original_title;
}, this);

        document.getElementById("possibleResults").innerText = content;

This is because 这是因为

document.getElementById("possibleResults").innerText = result.original_title;

every next iteration will overwrite the text inserted by previous one. 每次下一次迭代都将覆盖前一个插入的文本。

Try with 试试看

json.results.forEach(function(result) {
     console.log(result.original_title);
     document.getElementById("possibleResults").innerText += result.original_title

}, this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM