下面的代码应该从json对象中获取新闻源并以这样的堆叠格式将新闻打印在彼此之下
2013 - 1 - 新闻1 - 新闻2 - 2 - 新闻1 - 新闻2 2012 - 1 - 新闻1 - 新闻2 - 2 - 新闻1 - 新闻2
这是我的Feed
{
"currentYear": "2013",
"data": [
{
"id": "33",
"year": "2012",
"month": "3",
"day": "25",
"sourcename": "WSF",
"title": "Test",
"url": "www.test.com",
"ingress": "data"
},
{
"id": "72",
"year": "2012",
"month": "1",
"day": "20",
"sourcename": "SF times",
"title": "Test 1 ",
"url": "www.gogole.com",
"ingress": "data"
}
]
}
这是我的jquery
var date = new Date();
var currentYear = date.getFullYear();
var id;
var div_year_id;
var div_month_id;
var tmp_div_year_id;
var i = 1;
$.each(feed.data, function(key, val){
if(tmp_div_year_id != "#" + val.year) {
div_year_id = "#" + val.year;
div_month_id = "#" + val.year + "_" + val.month;
}
//check if the div for the year exists
if($(div_year_id).length > 0) {
console.log("adding year");
// check if the div for the month exists
if($(div_month_id).length > 0) {
console.log("adding month")
// append to the div year id
} else {
//create the month id
$(div_year_id).append('<div id='+ div_month_id + '></div>');
}
} else {
//create the year id
$("#news").append('<div id='+ div_year_id + '><div id='+ div_month_id +'><h1>' + val.title + '</h1><p><em>Date</em>: '+ val.year + '-' + val.month + '-' + val.day +'</p><p>' + val.ingress +'</p><p><em>Source</em>: '+ val.sourcename + '</em></p><p><a href="'+ val.url +'" target="_blank">Read full article >></a></p></div>');
$(div_year_id).append('<div id='+ div_month_id + '></div>');
tmp_div_year_id = div_year_id;
}
console.log(tmp_div_year_id);
i++;
});
代码不是每年在一个div中正确堆叠新闻,每年为每年创建一个新的div
答案 0 :(得分:1)
问题是你如何创建你的div;你正在创建它们,包括id中的#
字符。
我更改了您的代码(使用创建年份ID 注释查看主要的else语句)并在ID中创建#而不是#:
if ($(div_year_id).length > 0) {
console.log("adding year");
// check if the div for the month exists
if ($(div_month_id).length > 0) {
console.log("adding month")
// append to the div year id
} else {
//create the month id
$(div_year_id).append('<div id=' + val.month + '></div>');
}
} else {
//create the year id
$("#news").append('<div id=' + val.year + '><div id=' + val.month + '><h1>' + val.title + '</h1><p><em>Date</em>: ' + val.year + '-' + val.month + '-' + val.day + '</p><p>' + val.ingress + '</p><p><em>Source</em>: ' + val.sourcename + '</em></p><p><a href="' + val.url + '" target="_blank">Read full article >></a></p></div>');
$(div_year_id).append('<div id=' + val.month + '></div>');
tmp_div_year_id = div_year_id;
}
现在你的if语句按预期工作,工作小提琴:http://jsfiddle.net/IrvinDominin/K6aHe/3