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

使用jQuery实现点击语言按钮替换URL语言段并保留后续路径

解决语言切换时URL路径替换的问题

你的思路方向是对的,但代码里有几个细节问题导致功能失效,我帮你梳理并修正一下:

问题排查

  1. 大小写不匹配:你示例里的目标语言路径是/us_EN/,但代码里写的是/en_Us/,大小写不一致会让替换逻辑找不到匹配项
  2. 未阻止默认跳转行为:虽然用了javascript:void(0),但在点击事件里显式阻止默认行为能避免潜在的跳转异常
  3. 代码冗余:重复的URL替换逻辑可以合并优化,方便后续维护

修正后的完整代码

HTML部分

<div class="sidebar_lang">
  <span>Language:</span>
  <div class="lang_option">
    <a href="#" id='ger_btn' class="lang_txt">DE</a>
    <a href="#" id="eng_btn" class="lang_txt">EN</a>
  </div>
</div>

JavaScript部分

<script type="text/javascript">
// 确保DOM加载完成后再绑定事件
$(document).ready(function() {
  $("#eng_btn").click(function(event) {
    // 阻止a标签的默认跳转行为
    event.preventDefault();
    const currentUrl = window.location.href;
    // 精准匹配并替换语言路径段
    const newUrl = currentUrl.replace("/de_DE/", "/us_EN/");
    window.location.href = newUrl;
  });

  $("#ger_btn").click(function(event) {
    event.preventDefault();
    const currentUrl = window.location.href;
    const newUrl = currentUrl.replace("/us_EN/", "/de_DE/");
    window.location.href = newUrl;
  });
});
</script>

进阶优化方案

如果后续需要新增更多语言,可以把切换逻辑封装成通用函数,减少重复代码:

<script type="text/javascript">
$(document).ready(function() {
  // 通用语言切换函数
  function switchLanguage(fromLang, toLang) {
    return function(event) {
      event.preventDefault();
      const currentUrl = window.location.href;
      const newUrl = currentUrl.replace(`/${fromLang}/`, `/${toLang}/`);
      window.location.href = newUrl;
    };
  }

  // 绑定按钮事件
  $("#eng_btn").click(switchLanguage("de_DE", "us_EN"));
  $("#ger_btn").click(switchLanguage("us_EN", "de_DE"));
});
</script>

注意事项

  • 务必确保页面已经正确引入jQuery库,否则$符号会触发报错
  • 确认网站URL的语言路径格式确实是/xx_XX/的形式,这样替换规则才能精准生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:40:58