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

如何合并小时数组拆分与渲染操作以实现分页功能?

合并小时天气数据的拆分与渲染逻辑

已完成一个源自YouTube的项目,目前有168个hourRowElement被添加到hourlySection中。为实现分页系统,编写了splitHours函数将数组拆分为更小分组,请问如何将数组拆分与渲染这两个操作合并为一个?

你可以将数组拆分的逻辑直接整合到渲染函数中,根据分页需求完成数据处理与DOM渲染的统一操作。以下是两种常见的实现方式:

方式一:渲染指定页码的小时数据

这种方式会根据传入的页码,只渲染对应分组的内容,适合基础分页场景:

const HOUR_FORMATTER = new Intl.DateTimeFormat(undefined, { hour: "numeric" })
const hourlySection = document.querySelector("[data-hour-section]");
const hourRowTemplate = document.getElementById("hour-row-template");

// 合并拆分与渲染的分页渲染函数
function renderHourlyWeatherByPage(hourly, chunkSize = 6, currentPage = 1) {
  hourlySection.innerHTML = "";
  
  // 内部完成数组拆分逻辑
  const hourChunks = [];
  let index = 0;
  while (index < hourly.length) {
    hourChunks.push(hourly.slice(index, index + chunkSize));
    index += chunkSize;
  }

  // 获取当前页对应的分组(页码从1开始,索引需减1)
  const currentChunk = hourChunks[currentPage - 1] || [];

  // 渲染当前分组的小时数据
  currentChunk.forEach(hour => {
    const hourRowElement = hourRowTemplate.content.cloneNode(true);
    setValue("day", DAY_FORMATTER.format(hour.timestamp), { parent: hourRowElement});
    setValue("time",HOUR_FORMATTER.format(hour.timestamp) , { parent: hourRowElement});
    hourRowElement.querySelector("[data-icon]").src = getIconUrl(hour.iconCode);
    setValue("temp", hour.temp, { parent: hourRowElement });
    setValue("precip-percent", hour.chanceOfPrecip, { parent: hourRowElement });
    setValue("fl-temp", hour.feelsLike, { parent: hourRowElement });
    setValue("wind", hour.windSpeed, { parent: hourRowElement});
    setValue("precip-amount", hour.precipAmount, { parent: hourRowElement });
    setValue("humidity", hour.humidity, { parent: hourRowElement });
    setValue("dew-point", hour.dewPoint, { parent: hourRowElement });
    hourlySection.append(hourRowElement);
  });

  // 返回总页数,方便生成分页控件
  return hourChunks.length;
}

// 使用示例
function renderWeather({ hourly }) {
  const totalPages = renderHourlyWeatherByPage(hourly, 6);
  console.log(`总页数:${totalPages}`);
  // 此处可根据totalPages生成分页按钮、页码切换逻辑等
}

方式二:一次性渲染所有分组(带分组容器)

这种方式会把所有分组都渲染到页面,用容器包裹每个分组,通过控制容器的显示/隐藏来实现分页切换,适合不需要重新请求数据的前端分页:

const HOUR_FORMATTER = new Intl.DateTimeFormat(undefined, { hour: "numeric" })
const hourlySection = document.querySelector("[data-hour-section]");
const hourRowTemplate = document.getElementById("hour-row-template");

// 合并拆分与渲染的分组渲染函数
function renderHourlyWeatherWithChunks(hourly, chunkSize = 6) {
  hourlySection.innerHTML = "";
  
  // 内部完成数组拆分逻辑
  const hourChunks = [];
  let index = 0;
  while (index < hourly.length) {
    hourChunks.push(hourly.slice(index, index + chunkSize));
    index += chunkSize;
  }

  // 遍历每个分组,用容器包裹后渲染
  hourChunks.forEach((chunk, chunkIndex) => {
    const chunkContainer = document.createElement('div');
    chunkContainer.classList.add('hour-chunk');
    // 默认只显示第一页的分组
    if (chunkIndex !== 0) {
      chunkContainer.style.display = 'none';
    }

    // 渲染当前分组内的小时数据
    chunk.forEach(hour => {
      const hourRowElement = hourRowTemplate.content.cloneNode(true);
      setValue("day", DAY_FORMATTER.format(hour.timestamp), { parent: hourRowElement});
      setValue("time",HOUR_FORMATTER.format(hour.timestamp) , { parent: hourRowElement});
      hourRowElement.querySelector("[data-icon]").src = getIconUrl(hour.iconCode);
      setValue("temp", hour.temp, { parent: hourRowElement });
      setValue("precip-percent", hour.chanceOfPrecip, { parent: hourRowElement });
      setValue("fl-temp", hour.feelsLike, { parent: hourRowElement });
      setValue("wind", hour.windSpeed, { parent: hourRowElement});
      setValue("precip-amount", hour.precipAmount, { parent: hourRowElement });
      setValue("humidity", hour.humidity, { parent: hourRowElement });
      setValue("dew-point", hour.dewPoint, { parent: hourRowElement });
      chunkContainer.append(hourRowElement);
    });

    hourlySection.append(chunkContainer);
  });

  // 返回所有分组容器,方便后续实现分页切换逻辑
  return hourlySection.querySelectorAll('.hour-chunk');
}

// 使用示例
function renderWeather({ hourly }) {
  const chunkContainers = renderHourlyWeatherWithChunks(hourly, 6);
  // 例如点击页码按钮时,切换对应容器的显示状态
  // chunkContainers[pageIndex].style.display = 'block';
}

核心思路

将原本独立的splitHours拆分逻辑,直接嵌入到渲染函数内部,避免额外的函数调用开销。同时根据分页场景的需求,直接在渲染阶段处理数据分组,让数据处理与DOM渲染的逻辑更紧凑,也更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:45