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

请求编写基于URL路径的动态按钮链接生成JavaScript代码

解决方案

翻译后的按钮HTML模板

<a class="button_green" href="example.com/b/%num_up%/" rel="">继续前往B%num_up%</a>
<a class="button_blue" href="example.com/%letter_up%/002/" rel="">跳转至%letter_up%2</a>
<a class="button_green" href="example.com/b/%num_down%/" rel="">返回至B%num_down%</a>

JavaScript实现代码

// 获取当前页面路径
const currentPath = window.location.pathname;
// 匹配路径中的字母(a/b)和三位数字
const pathMatch = currentPath.match(/^\/([ab])\/(\d{3})\/$/);

if (pathMatch) {
  const [, currentLetter, currentNumStr] = pathMatch;
  const currentNum = parseInt(currentNumStr, 10);
  
  // 格式化数字为三位带前导零的字符串
  const formatNum = (num) => num.toString().padStart(3, '0');
  
  let numUp, numDown, letterUp;
  
  if (currentLetter === 'a') {
    // 当前处于/a/xxx/路径
    numUp = currentNumStr;
    numDown = formatNum(currentNum - 1);
    letterUp = 'a';
  } else {
    // 当前处于/b/xxx/路径
    numUp = formatNum(currentNum + 1);
    numDown = formatNum(currentNum - 1);
    letterUp = 'a';
  }
  
  // 生成按钮HTML
  const buttonHTML = `
    <a class="button_green" href="example.com/b/${numUp}/" rel="">继续前往B${numUp}</a>
    <a class="button_blue" href="example.com/${letterUp}/002/" rel="">跳转至${letterUp}2</a>
    <a class="button_green" href="example.com/b/${numDown}/" rel="">返回至B${numDown}</a>
  `;
  
  // 将按钮插入页面底部(可替换为你实际的容器选择器)
  const targetContainer = document.getElementById('footer-buttons') || document.body;
  targetContainer.insertAdjacentHTML('beforeend', buttonHTML);
} else {
  console.log('当前路径不符合/a/xxx/或/b/xxx/格式');
}

逻辑说明

  • 路径匹配:通过正则提取路径中的字母标识和三位数字编号
  • 数字格式化:确保加减后的数字始终保持三位格式(补前导零)
  • 按钮规则对应:
    • 处于/a/001/时:
      继续按钮→example.com/b/001/,跳转按钮→example.com/a/002/,返回按钮→example.com/b/000/
    • 处于/b/003/时:
      继续按钮→example.com/b/004/,跳转按钮→example.com/a/002/,返回按钮→example.com/b/002/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:32