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

如何用JavaScript/jQuery将旧URL查询参数携带到新跳转URL?

解决方案

问题分析

你的代码核心问题是查询参数的获取时机和URL拼接格式:

  • 原代码在页面加载时就固定了urlParams的值,若后续页面URL参数有变更,会导致携带旧参数;
  • 拼接的/test/ + urlParams 会生成/test/?xxx格式的URL,部分服务器会将/test/识别为目录路径,可能引发参数解析异常(或不符合你期望的/test?xxx无斜杠格式)。

修复后的代码

方式1:原生JS(推荐)

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.money').forEach(function(el) {
        el.addEventListener('click', function() {
            // 点击时实时获取当前URL的查询参数
            const urlParams = window.location.search;
            // 拼接正确的目标URL(去掉/test后面的斜杠)
            window.location.href = '/test' + urlParams;
        });
    });
});

方式2:jQuery版本

$(document).ready(function() {
    $('.money').on('click', function() {
        const urlParams = window.location.search;
        window.location.href = '/test' + urlParams;
    });
});

更健壮的URL处理方式(使用URL API)

如果需要对参数进行修改或校验,推荐用浏览器原生URL对象,避免手动拼接出错:

$(document).ready(function() {
    $('.money').on('click', function() {
        const currentUrl = new URL(window.location.href);
        // 可在这里灵活修改参数,例如:currentUrl.searchParams.set('newKey', 'newValue');
        const targetUrl = new URL('/test', window.location.origin);
        targetUrl.search = currentUrl.search;
        window.location.href = targetUrl.toString();
    });
});

这个方式会自动处理URL格式问题,确保参数正确携带,同时支持灵活调整查询参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:46:06