You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery按日期排序JSON数据并在表格中添加日期分隔标识

修改方案

通过新增变量记录上一条航班的到达日期,检测到日期变更时先插入跨全列的日期展示行即可实现需求,修改后的JS代码如下:

function airport() {
    var airport_data = ""
    // 存储上一条航班的日期,初始值为空
    let lastFlightDate = ''
    $.ajax('my_airport.json', {
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        cache: false,
    }).done(function (data, textStatus, jqXHR) {
        data.forEach(element => {
            if (element.flight.status.generic.status.text == 'scheduled') {
                const arrivalTimestamp = element.flight.time.scheduled.arrival
                // 处理到达时间为空的情况
                if (!arrivalTimestamp) {
                    airport_data += "<tr><td colspan='6'><p>N/A</p></td></tr>"
                    return
                }
                // 格式化当前航班的完整日期
                const currentDate = moment.unix(arrivalTimestamp).format("YYYY年MM月DD日")
                // 日期发生变化时插入日期行
                if (currentDate !== lastFlightDate) {
                    airport_data += `<tr><td colspan="6" style="font-weight: bold; text-align: left; padding: 8px 15px; background: #f0f0f0">${currentDate}</td></tr>`
                    lastFlightDate = currentDate
                }
                // 原有航班行拼接逻辑
                airport_data += '<tr>';
                airport_data += '<td><p>' + element.flight.airline.name + '</p></td>';
                airport_data += '<td><p>' + element.flight.identification.number.default + '</p></td>';
                if (element.flight.aircraft == null) {
                    airport_data += '<td><p>N/A</p></td>';
                } else {
                    airport_data += '<td><p>' + element.flight.aircraft.model.code + '</p></td>';
                }
                airport_data += '<td><p>' + element.flight.airport.origin.position.region.city + '</p></td>';
                airport_data += '<td><p>' + moment.unix(arrivalTimestamp).format("h:mm a") + '</p></td>';
                airport_data += '<td><p>' + element.flight.status.generic.status.text + '</p></td>';
            }
        })
        // DOM操作移到循环外,避免重复渲染损耗性能
        document.getElementById("data").innerHTML = airport_data
        var rows = $("#data");
        rows.hide();
        $('.row-data:last-child').after(rows);
        rows.fadeIn(500);
    })
}

说明

  • 日期行设置了colspan="6"属性占满表格整行,样式可根据实际需求调整
  • 原代码将DOM更新逻辑放在forEach循环内部,会导致每处理一条数据就重渲染一次表格,修改后移到循环外,运行性能更高
  • 日期展示格式可通过修改moment.format()的参数自定义,比如修改为MM/DD/YYYY即可适配月/日/年的展示习惯

内容的提问来源于stack exchange,提问作者Ali Ghassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:36:03