下面的代码应该从 json 对象中获取新闻提要,并以像这样的堆叠格式在彼此下方打印新闻
2013 - 1 - 新闻 1 - 新闻 2 - 2 - 新闻 1 - 新闻 2 2012 - 1 - 新闻 1 - 新闻 2 - 2 - 新闻 1 - 新闻 2
这是我的饲料
{
"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