使用 javascript 捕获用户在 URL 上输入的查询

Use javascript to capture query entered by user on the URL

我正在开发一个项目,用户希望能够在 URL 的末尾添加“?2yr”或“?4yr”,但是当用户点击另一个页面也传递该查询。

例如,http://example.com/index.html?2yr is the home page, but when you click say contact it would be http://example.com/powerful_predictors.html?2yr.

我已尝试执行以下操作:

var _url = window.location;


if(window.location.href.indexOf("2yr") >- 1) {
    console.log("your url contains the 2yr");

} else if(window.location.href.indexOf("4yr") >-1){ 
    console.log("your url contains 4yr");
}

当用户单击 URL 转到另一个页面时,如何添加“?2yr”或“?4yr”?

您可以遍历所有锚标记,并修改 属性 href 以添加查询字符串:

document.addEventListener('DOMContentLoaded', function() {
  [].forEach.call(document.querySelectorAll('a[href]'), function(el, i) {
    el.href = el.href + location.search;
  });
});

这个问题有几个解决方案,但首先,我会为您的 JavaScript 代码推荐一个更好的参数解析器。

This is a much more robust solution

到位,你有两个解决方案。

一个是在页面开始时,运行 循环并使用您之前检索到的 HTML 参数更新所有 a#href 属性。如果您提供的是静态内容,则此方法有效。如果您有任何动态内容,它很快就会崩溃。

因此,下一个解决方案是设置一个 delegated event——基本上,您将一个 click 事件附加到 body 元素,然后检查实际元素是什么点击是。

You can learn more here.