我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
当前回答
这是更改URL参数的现代方法:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
其他回答
您可以使用我的这个库来完成这项工作:https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
想想这个例子:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
它会做和你要求的完全一样的事情。请注意URL必须有正确的格式。在你的例子中,你必须指定协议(http或https)
我认为你需要查询插件。
例如:
window.location.search = jQuery.query.set("rows", 10);
不管行当前的状态如何,这都可以工作。
四年后,在我学到了很多东西之后,来回答我自己的问题。特别是你不应该对所有事情都使用jQuery。我已经创建了一个简单的模块,可以解析/stringify查询字符串。这使得修改查询字符串变得很容易。
query-string的用法如下:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
Ben Alman有一个很好的jquery querystring/url插件,可以让你很容易地操纵querystring。
如要求-
点击这里进入他的测试页面
在firebug中,在控制台中输入以下内容
jQuery.param.querystring (window.location。报道中,x = 3&newValue = 100);
它将返回以下修改后的url字符串
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
注意,a的查询字符串值已从X更改为3,并添加了新值。
然后你可以使用新的url字符串,但你希望 使用文档。location = newUrl或改变一个锚链接等