javascript 跟随链接时如何保留 URL 查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15579070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep URL query parameters when following a link?
提问by Denys Séguret
This is the code of login.html:
这是login.html的代码:
<ul>
<li class="introduction">
<a href="introduction.html">
<span class="icon"></span>
Introduction
</a>
</li>
<li class="login active">
<a href="#">
<span class="login"></span>
Login
</a>
</li>
</ul>
An external link will first take to the current page (login) with some query parameters I want to keep. If the user clicks the first link introduction
, the introduction.html will be loaded. However, all the query parameter of the previous page (login) are lost.
外部链接将首先使用我想保留的一些查询参数转到当前页面(登录)。如果用户单击第一个链接introduction
,将加载 Introduction.html。但是,上一页(登录)的所有查询参数都丢失了。
Is there anyway I can do this page load while keeping the query parameters? Either using HTML or Javascript.
无论如何,我可以在保留查询参数的同时加载此页面吗?使用 HTML 或 Javascript。
Many thanks.
非常感谢。
回答by Denys Séguret
回答by Matt Stone
Automatically append your current params to any links you deem worthy via a rel=""
attribute on <a>
tags (using jQuery):
通过标签上的rel=""
属性<a>
(使用 jQuery)自动将您当前的参数附加到您认为值得的任何链接:
<a href="introduction.html" rel="keep-params">Link</a>
// all <a> tags containing a certain rel=""
$("a[rel~='keep-params']").click(function(e) {
e.preventDefault();
var params = window.location.search,
dest = $(this).attr('href') + params;
// in my experience, a short timeout has helped overcome browser bugs
window.setTimeout(function() {
window.location.href = dest;
}, 100);
});