javascript - 循环中的 If 语句填充表 jQuery

标签 javascript jquery loops if-statement

我正在使用 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。 (单元格命名为:wed09wed10wed11wed12wed13 , 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/

相关文章:

javascript - 为什么 object.keys() 到对象文字和 Object.create() 有不同的结果?

javascript - 如何根据类型字符串在 javascript 中创建新对象?

javascript - 如何通过 JSON 更新 msDropDown 列表?

javascript - 正则表达式查找以 # 开头直到空格的字符串

ios - 用于 iOS 推送通知的 PHP,有时超过 1 台设备

javascript - 将 evt 监听器附加到动态创建的类

bash - 如何在 bash 中循环遍历字母表的前 n 个字母

javascript - Angular.forEach 只返回一个结果?

jquery maxlength "æ"或 "ø"或 "å"应计为两个字符

javascript - 使用 JavaScript 生成时 Html 代码无法正常工作