gpt4 book ai didi

jQuery JSON .each 错误

转载 作者:行者123 更新时间:2023-12-01 07:35:11 25 4
gpt4 key购买 nike

我有一个如下所示的 JSON 对象。

[
{
"id" : "23",
"event_id" : "0",
"sport_title" : null,
"event_title" : null,
"title" : "Under 1 day!",
"content" : "It\\'s all hotting up and battle commences in under one day!",
"link" : ""
},

{
"id" : "20",
"event_id" : "0",
"sport_title" : null,
"event_title" : null,
"title" : "Getting Exciting",
"content" : "Less than two days till it all kicks off, with cricket....",
"link" : ""
}
]

我试图从这个 JSON 对象中获取详细信息,并将它们添加到 <ul> 前面。

我当前正在尝试的代码看起来像这样并且有问题

var writeup_list = writeuplist;

$.getJSON('../json/getWriteups.json', function(data) {

$.each(data.items, function(i, item) {
writeup_list.html(function() {
var output;
output = '<li><a href="/writeups/index.php#writeup_' + item.id + '">';
if(item.sport_title != null) {
output += item.sport_title + ' - ';
}
output += item.title + '</a></li>';

return output;
});
});

});

writeuplist 只是 ul 对象。

我还担心会覆盖列表中已有的信息或只是再次添加。不想继续添加相同的数据。有什么好方法可以避免这种情况?

我似乎在从 JSON 文件中获取数据时遇到问题,我相信这与我尝试在 .each 函数中访问它的方式有关。

有人能发现哪里出了问题吗?

最佳答案

jQuery.getJSON('../json/getWriteups.json', function(data) {
var output = '';

jQuery.each(data.items, function (index, item) {
output += '<li><a href="/writeups/index.php#writeup_' + item.id + '">';

if (typeof item.sport_title == "string") {
output += item.sport_title + ' - ';
}

output += item.title + '</a></li>';
});

writeup_list.html(output);
});

一些注意事项:

  1. 您确定 data.items 是访问数组的正确方法吗? (尝试在回调中执行alert(data.items),并确保您看到[object Array])。
  2. 您确定 item.sport_title 将为 null 吗?我更改了它以检查它的字符串...
  3. 在进行过程中构建列表元素的字符串,然后在最后将其添加到 DOM 中,这比在过程中将元素添加到 DOM 中更快。
  4. 执行 element.html(str) 将替换当前内容。您的示例在每次迭代时都会替换当前的 html,因此最后,您只会拥有列表中最后一个列表元素的内容。

关于jQuery JSON .each 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2733730/

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