jquery.append() - only the last element of my list is appended, previous ones are erased
I have a page like this :
<div id="daysTable">
<div id="day0" class="day"></div>
<div id="day1" class="day"></div>
<div id="day2" class="day"></div>
<div id="day3" class="day"></div>
<div id="day4" class="day"></div>
<div id="day5" class="day"></div>
<div id="day6" class="day"></div>
</div>
and some javascript to fill my calendar like this
function getWeek(){
$.getJSON("/getWeek",function(events){
var eventHeight = $("#hoursTable > div").height();
var eventWidth = $("#daysTable > div").width();
var startWeek = events[0]// timestamp of the start of the week
for(var i = 1; i < events.length; i ++){
$(".day").empty();
var startHour = (events[i].startDate - startWeek)/3600
var duration = (events[i].stopDate - startWeek)/3600 - startHour
var dayStart = Ma开发者_Go百科th.floor(startHour/24);
var startHour = startHour - dayStart * 24
divEvent = $('<div id="event'+events[i].idEvent+'"/>')
.width(eventWidth-2)
.height(duration*eventHeight)
.css("border","1px solid black")
.css("margin-top",startHour*eventHeight)
.html(events[i].name);
divEvent.appendTo("#day"+dayStart);
console.log(divEvent);
}
});
}
my problem being : events contain 3 element I'd like to display but only the last is displayed. If I stop my "for" at the first iteration I can see the first div appended, but it seems that if my loop goes for three iteration the two previous are deleted. The console.log() display some "not-anymore" existing element. Any idea ?
By calling $(".day").empty();
at the top of the loop, you're removing all of the events before you add each new one.
You need to move that line before the for
loop.
Inside your loop you're calling $(".day").empty();
which is erasing any added in previous iterations...you need to move that outside/before the for
loop so it doesn't do this anymore.
So this:
for(var i = 1; i < events.length; i ++){
$(".day").empty();
Should be this:
$(".day").empty();
for(var i = 1; i < events.length; i ++){
can we see the returned structure of your "/getWeek"
json....
cause I think the issue is that in function(events){...}
, events
is not an array...
I think you should have something like events.data.length
, then events.data[i].somevariable
精彩评论