使用 jQuery 更改 url 查询字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17211736/
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
Change url query string value using jQuery
提问by Cameron
I have an example URL like:
我有一个示例 URL,如:
http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01
http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01
The query string contains the current page number and two additional filters (name and date).
查询字符串包含当前页码和两个附加过滤器(名称和日期)。
Using the following URL parser: https://github.com/allmarkedup/purlI am able to access certain parts of the URL such as just the page number.
使用以下 URL 解析器:https: //github.com/allmarkedup/purl我能够访问 URL 的某些部分,例如页码。
I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.
我正在尝试为用户创建一种方法,使用户能够在文本框中键入一个数字,然后加载该页码,同时保持所有其他查询字符串不变。
$(document).ready(function () {
$('.pageNum').live('keyup', function (e) {
e.preventDefault();
if (e.which == 13) {
var currentUrl = window.location.href;
var parsedUrl = $.url(currentUrl);
var currentPageNum = parsedUrl.param('page');
var newPageNum = $(this).val();
var newUrl = //
window.location.href = newUrl;
}
});
});
So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.
因此,当用户在 pageNum 文本框上点击 return 时,它将获取当前页面 url,解析它,然后找出当前页码,然后我需要一种方法将页码的值替换为文本框中的新值创建一个新的 url,然后最后使用这个新的 url 刷新页面。
Is it possible to change the param value and then add it back in?
是否可以更改参数值然后重新添加?
Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!
注意:附加参数可以是任何东西,所以我不能手动将它们添加到带有新页码的路径名中!
回答by Kaizo
If you only need to modify the page num you can replace it:
如果你只需要修改page num你可以替换它:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
回答by Andreas
purls $.params()
used without a parameter will give you a key-value object of the parameters.
$.params()
不带参数使用的purls将为您提供参数的键值对象。
jQuerys $.param()
will build a querystring from the supplied object/array.
jQuery$.param()
将从提供的对象/数组构建查询字符串。
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete
here...
更新
我不知道为什么我delete
在这里使用...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);