我正在使用jQuery填写时间表信息,信息以JSON格式提供。这是我正在使用的循环:
for (var i = 0; i < r.events.length; i++) {
myvar = r.events[i].slot;
$("#" + myvar).text( r.desc + r.events[i].type + r.events[i].rooms +
r.events[i].id + r.events[i].duration );
所以我需要在循环中插入if
语句,如果事件的持续时间等于2,则循环填充单元格AND单元格+1。 (单元格命名为:wed09
,wed10
,wed11
,wed12
,wed13
,wed14
,wed15
,{{ 1}},wed16
,thu09
等等。)
我该怎么编码?
非常感谢
答案 0 :(得分:1)
我认为最好的方法是拥有一个像这样的TimeTable类:
var TimeTable = function(currentCell) {
var days = ["mon", "tue", "wed", "thu", "fri"];
var hours = ["09", "10", "11", "12", "13", "14", "15", "16"];
var currentDay = days.indexOf(currentCell.substring(0,3));
var currentHour = hours.indexOf(currentCell.substring(3));
// nextCell: updates the values on the TimeTable object
var nextCell = function () {
var lastDay = days.length - 1;
if (currentHour === hours.length - 1) {
currentHour = 0;
currentDay++;
} else {
currentHour++;
}
}
// getNextCell: gets the current Cell and increments the next cell
getNextCell = function () {
var currentCell = days[currentDay] + hours[currentHour];
nextCell();
return currentCell;
}
// fill: fills (duration) times the adjacent cells
// input duration: the duration of the event ( > 0 )
// input text: the text that needs to be filled into each cell
this.fill = function (duration, text) {
for (var i = 0; i < duration; i++) {
$("#" + getNextCell()).text(text);
}
}
}
由于你谈到的持续时间可能是2或更高,我在fill
方法中使用了for循环而不是if,所以如果持续时间= 3等,则会填充3个单元格。
最后,您需要像这样替换for
循环:
for (var i = 0; i < r.events.length; i++) {
var timeTable = new TimeTable(r.events[i].slot);
text = r.desc + '\n' + r.events[i].type + '\n' + r.events[i].rooms + '\n' + r.events[i].id + r.events[i].duration;
timeTable.fill(r.events[i].duration, text);
}
代码位于this fiddle