首页 > 解决方案 > 在 URL 中添加一个变量而不是替换一个

问题描述

我遇到了一个 javascript 脚本的小问题。我正在尝试使我的网站多语言。全部设置在数据库中,我的选择适用于 URL 没有变量的页面。这是我的脚本:

<script type="text/javascript">
    function submitForm() {
        var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
        window.location.href = window.location.pathname + '?lang=' + thelang;
    }
</script>

在主页的情况下,它可以工作,并http://localhost/通过http://localhost/?lang=en

但是当我有一个已经设置变量的 URL 时,它会替换它。从http://localhost/modules/product/product.php?id=1我有http://localhost/modules/product/product.php?lang=en,我想要的结果是:

http://localhost/modules/product/product.php?id=1&lang=en

如何修复脚本以使其在两种情况下都能正常工作,或者添加变量,或者将它与现有的绑定?

标签: javascript

解决方案


尝试检查 URL 中是否已存在查询字符串参数。

function submitForm() {
  var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;

  if (window.location.href.indexOf('?') >= 0) {
    // There are already querystring params in the URL. Append my new param.
    window.location.href = window.location.href + '&lang=' + thelang;
  } else {
    // There are not querystring params in the URL. Create my new param.
    window.location.href = window.location.href + '?lang=' + thelang;
  }
}

更新:说明后续的语言变化

这假定 lang 值将始终是两个字符。

function submitForm() {
  var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
  var newUrl = window.location.href;
  var langIndex = newUrl.indexOf('lang=');

  if (langIndex >= 0) {
    // Lang is already in the querystring params. Remove it.
    newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
  }

  // Remove the final '?' or '&' character if there are no params remaining.
  newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;

  newUrl = newUrl.indexOf('?') >= 0
    ? newUrl + '&lang=' + thelang  // There are already querystring params in the URL. Append my new param.
    : newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.

  window.location.href  = newUrl;
}

推荐阅读