使用javascript显示循环的所有结果

Showing all the results of a loop with javascript?

本文关键字:结果 循环 javascript 显示 使用      更新时间:2023-09-26

我迷路了。我是javascript/jQuery的新手。我在JSON中做了一个循环:

  <script type="text/javascript">
   var geturl = "http://couponsforweed.com/?json=get_recent_posts";
            $.ajax({
                type:'GET',
                url:geturl,
                complete: function(){                    
                },
                success: function (data) {
                    var response = data; //JSON.parse(data);
                    // it works!
                    alert("status: " + response.status + "'ncount: " + response.count + "'npages: " + response.pages + "'ncount_total: " + response.count_total + "'nposts: " + response.posts.length);

                    //loop through posts
                    for(var i = 0; i != response.posts.length; i++) {
                        //get each element in the array
                        var post = response.posts[i];

                        // output stuff so we can see things
                        output.innerHTML = i + " post: " + post.custom_fields.schemaState;
                    }

                },
                error:function (xhr, ajaxOptions, thrownError) {                    
                    alert("Error");
                }
            });
  </script>

它起作用了,我很高兴自己能做到这一点。但我的问题是:

// output stuff so we can see things
   output.innerHTML = i + " post: " + post.custom_fields.schemaState;

为什么这只给我循环中的最后一个结果,而不是循环中所有结果的列表?

我得到:

9 Ca

我想看看(循环中的每个结果):

1 Ca2 Ca3 Ca4 Ca5钴6瓦7钴8 Ca9 Ca

我习惯了WordPress中的PHP循环,在那里你可以循环浏览每个帖子的所有字段,并得到相应的结果。

每次都设置output.innerHTML,有效地删除了以前迭代的结果。代替:

output.innerHTML = i...

简单使用:

output.innerHTML += i...

附加到变量而不是设置变量。不过,更好的选择是创建一个临时变量。例如,如果您将其命名为foo:

foo += i...

每次迭代,然后在循环结束时:

output.innerHTML = foo

这将大大提高效率,因为它只在循环结束时更新DOM一次。

您应该在处附加一个"+="而不是一个"="

output.innerHTML = i + " post: " + post.custom_fields.schemaState;

所以看起来像

output.innerHTML += i + " post: " + post.custom_fields.schemaState;