[英]How do you add a parameter to a URL and reload the page
I'm looking for the simplest way to add parameters to a URL and then reload the page via javascript/jquery. 我正在寻找向URL添加参数,然后通过javascript / jquery重新加载页面的最简单方法。 I'm trying to avoid any plugins.
我正在尝试避免使用任何插件。 Essentially I want:
本质上我想要:
http://www.mysite.com/about
to become: 成为:
http://www.mysite.com/about?qa=newParam
or, if a parameter already exists, then add a second parameter: 或者,如果参数已经存在,则添加第二个参数:
http://www.mysite.com/about?qa=oldParam&qa=newParam
location.href
will give you the current URL. location.href
将为您提供当前URL。 You can then edit your query string and refresh the page by doing something like this: 然后,您可以编辑查询字符串并通过执行以下操作刷新页面:
if (location.href.indexOf("?") === -1) {
window.location = location.href += "?qa=newParam";
}
else {
window.location = location.href += "&qa=newParam";
}
Have a look at Window.location (MDN) for information on window.location
. 查看window.location(MDN),以获取有关
window.location
信息。
A quick and dirty solution is: 一个快速而肮脏的解决方案是:
location += (location.search ? "&" : "?") + "qa=newParam"
It should work for your example, but misses some edge cases. 它适用于您的示例,但是遗漏了一些极端情况。
Here is a vanilla solution, it should work nicely for all cases (except wrong inputs of course). 这是一个很好的解决方案,它在所有情况下都可以很好地工作(当然,错误的输入除外)。
function replace_search(name, value) {
var str = location.search;
if (new RegExp("[&?]"+name+"([=&].+)?$").test(str)) {
str = str.replace(new RegExp("(?:[&?])"+name+"[^&]*", "g"), "")
}
str += "&";
str += name + "=" + value;
str = "?" + str.slice(1);
// there is an official order for the query and the hash if you didn't know.
location.assign(location.origin + location.pathname + str + location.hash)
};
EDIT: if you want to add stuff and never remove anything the function is way smaller. 编辑:如果您想添加东西而从不删除任何内容,则该函数要小得多。 I'm not very found of having multiple fields with different values but there is no specifications on that.
我不是很想知道具有多个具有不同值的字段,但是对此没有任何说明。
function replace_search(name, value) {
var str = "";
if (location.search.length == 0) {
str = "?"
} else {
str = "&"
}
str += name + "=" + value;
location.assign(location.origin + location.pathname + location.search + str + location.hash)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.