我正在使用 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
, wed16
, thu09
, thu10
等等。)
我该如何编码?
非常感谢
最佳答案
我认为最好的办法是有一个像这样的 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,所以如果 duration = 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
关于javascript - 循环中的 If 语句填充表 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023900/