gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:57:13 24 4
gpt4 key购买 nike

我迷路了。我是 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钙

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

1钙2钙3钙4钙5钴6瓦7钴8钙9钙

我习惯于在 WordPress 中使用 PHP 循环,您可以在其中循环遍历每个帖子的所有字段并相应地获得结果。

最佳答案

您每次都在设置 output.innerHTML,有效地删除了先前迭代的结果。而不是:

output.innerHTML = i...

只需使用:

output.innerHTML += i...

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

foo += i...

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

output.innerHTML = foo

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

关于javascript - 使用 javascript 显示循环的所有结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com