You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript分页URL更新问题:如何将URL改为?page={pageNumber}

解决分页时URL同步更新的问题

看起来你已经把分页的核心浏览功能实现得很完善了,就差URL同步这最后一步!要让URL随着页码切换更新为domain.com/search/?page={pageNumber}的格式,我们可以利用浏览器的History API来实现无刷新修改URL,同时还要处理页面初始化、浏览器前进后退的场景,保证用户体验一致。下面是具体的修改方案:

1. 新增URL更新函数

先写一个通用函数来处理URL的page参数更新,它会保留现有URL的其他查询参数,只修改或移除page参数(当页码为1时移除,让URL更整洁):

function updatePageUrl(pageNumber) {
  // 解析当前URL的查询参数
  const params = new URLSearchParams(window.location.search);
  // 根据页码处理page参数:页码为1时移除,否则更新
  if (pageNumber === 1) {
    params.delete('page');
  } else {
    params.set('page', pageNumber);
  }
  // 构造新的URL路径和查询参数
  const newUrl = `${window.location.pathname}${params.toString() ? `?${params.toString()}` : ''}`;
  // 使用pushState更新URL,不会触发页面刷新
  window.history.pushState({ page: pageNumber }, '', newUrl);
}

2. 修改分页事件监听器

在你现有的三个分页事件处理函数中,调用完apiresultFn加载数据后,添加updatePageUrl来同步更新URL:

上一页按钮事件

const prevBtnClick = () => {
  if (currentPage > 1) {
    currentPage--;
    // 更新下拉菜单的选中项(索引从0开始,页码从1开始,所以减1)
    document.getElementById("page-no").selectedIndex = currentPage - 1;
    apiresultFn(animalType, searchLocation, currentPage);
    // 同步更新URL
    updatePageUrl(currentPage);
  }
};

下一页按钮事件

const nextBtnClick = () => {
  if (currentPage < totalPages) {
    currentPage++;
    document.getElementById("page-no").selectedIndex = currentPage - 1;
    apiresultFn(animalType, searchLocation, currentPage);
    updatePageUrl(currentPage);
  }
};

页码下拉选择事件

const optionSelect = (e) => {
  currentPage = parseInt(e.target.value);
  apiresultFn(animalType, searchLocation, currentPage);
  updatePageUrl(currentPage);
};

3. 初始化时从URL读取页码

为了让用户刷新页面或直接访问带page参数的URL时,能加载对应页码的数据,需要在页面初始化时从URL中读取page参数:

// 初始化currentPage:优先从URL取page参数,默认值为1
let currentPage = parseInt(new URLSearchParams(window.location.search).get('page')) || 1;

// 构建页码下拉菜单时,选中对应页码的选项
if (document.querySelector("#page-no").innerHTML === "") {
  for (let index = 1; index <= totalPages; index++) {
    let option = document.createElement("option");
    option.setAttribute("value", `${index}`);
    option.textContent = index;
    // 选中当前页码对应的选项,而不是固定选中第1项
    if (index === currentPage) {
      option.selected = true;
    }
    document.querySelector("#page-no").appendChild(option);
  }
}

// 页面加载时,根据初始化的currentPage加载对应数据
apiresultFn(animalType, searchLocation, currentPage);

4. 处理浏览器前进后退

当用户点击浏览器的前进/后退按钮时,需要同步更新页面内容,所以要监听popstate事件:

window.addEventListener('popstate', (event) => {
  if (event.state && event.state.page) {
    currentPage = event.state.page;
    // 更新下拉菜单的选中状态
    document.getElementById("page-no").selectedIndex = currentPage - 1;
    // 加载对应页码的数据
    apiresultFn(animalType, searchLocation, currentPage);
  }
});

这样修改后,你的分页功能就能实现URL和页码的同步更新了,用户可以直观看到当前页码,刷新页面或分享链接也能直接定位到对应页面~

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

火山引擎 最新活动