【问题标题】:Use javascript to capture query entered by user on the URL使用 javascript 捕获用户在 URL 上输入的查询
【发布时间】:2015-09-29 17:54:19
【问题描述】:

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

例如,http://example.com/index.html?2yr 是主页,但当您单击说联系时,它将是 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”?

【问题讨论】:

    标签: javascript query-string


    【解决方案1】:

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

    This is a much more robust solution

    这样,您有两个解决方案。

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

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

    You can learn more here.

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 您好 Buzinas,我尝试了您的代码,但它没有附加 URL 以包含查询字符串。
    • @kirdua 抱歉,这是一个错字。我已经确定了我的答案。看看我为你创建的pluker
    • 谢谢。有没有办法通过地址栏添加查询字符串。我的客户只想通过地址栏添加“?2yr”或“?4yr”,然后将其传递给所有其他href。
    • 答案中的代码已经做到了!尝试打开this link,然后将地址栏更改为?2yr,看看链接会发生什么。 :)
    • 但是如果你想在状态栏中显示链接,你应该改变href属性,而不是属性,例如:el.setAttribute('href', el.getAttribute('href') + location.search);
    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多