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

如何提取URL路径片段,点击按钮时拼接跳转链接并添加查询参数

实现方案

优先推荐方案(无URL解析错误风险)

如果你的站点支持在产品页渲染时注入自定义属性,直接把参数写入按钮DOM属性,是最稳妥的实现方式,不需要解析URL,适配所有艺术家slug命名规则:

  1. 按钮HTML代码:
<button id="contact-artist-btn" 
        data-artist-slug="smith-john" 
        data-product-slug="painting-1">
  联系我
</button>

注:其中data-artist-slug和data-product-slug的值由你的建站系统从产品数据中直接读取渲染,不需要手动修改每个产品页的代码

  1. 配套JS代码:
document.getElementById('contact-artist-btn').addEventListener('click', function() {
  // 直接读取按钮上预置的参数
  const artistSlug = this.dataset.artistSlug;
  const productSlug = this.dataset.productSlug;
  // 拼接跳转链接,自动处理编码避免特殊字符报错
  const targetUrl = `/contact/${artistSlug}/?product=${encodeURIComponent(productSlug)}`;
  window.location.href = targetUrl;
});

纯前端URL解析方案(无法注入属性时使用)

如果你的站点没办法直接渲染参数到DOM属性,可以通过解析当前页面URL生成跳转链接:

  1. 按钮HTML代码:
<button id="contact-artist-btn">联系我</button>
  1. 配套JS代码:
document.getElementById('contact-artist-btn').addEventListener('click', function() {
  // 提取当前URL路径中/product/后的内容
  const pathSegments = window.location.pathname.split('/').filter(segment => segment);
  const fullProductSlug = pathSegments[pathSegments.indexOf('product') + 1];
  const slugParts = fullProductSlug.split('-');

  // 按你的URL规则拆分:前两部分为艺术家slug,剩余为产品标识
  // 如果你的艺术家slug段数不固定,调整slice的结束位置即可
  const artistSlug = slugParts.slice(0, 2).join('-');
  const productIdentifier = slugParts.slice(2).join('-');

  // 拼接跳转链接
  const targetUrl = `/contact/${artistSlug}/?product=${encodeURIComponent(productIdentifier)}`;
  window.location.href = targetUrl;
});

联系页获取来源产品信息

如果需要在联系页获取用户来源的产品标识,可以用以下JS代码读取参数,可写入表单隐藏域随用户提交的内容一起收集:

const urlParams = new URLSearchParams(window.location.search);
const sourceProduct = urlParams.get('product');
if (sourceProduct) {
  // 假设你在联系表单里加了id为product_source的隐藏输入框
  document.getElementById('product_source').value = sourceProduct;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:06:03