let loc = new URL('http://example.com/?nr=1');
// loc is a placeholder for your window.location
let url = loc.href;
// here, url.search would be window.location.href.search
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
console.log(nr);
url = loc;
// here, url.search would be window.location.search
params = new URLSearchParams(url.search);
nr = params.has('nr')
console.log(nr);
从…起https://developer.mozilla.org/en-us/docs/web/api/urlsearchparams The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present. 因此,您应该只提供查询参数字符串。 e、 g.如果您的window.location.href
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var params = getUrlVars();
console.log(params["nr"]);
3条答案
按热度按时间v09wglhw1#
使用
因为window.location是具有
.search
财产而window.location.href是一个字符串,没有
.search
财产所以你
url.search
是undefined
我可以用它来演示URL
类似于Location
在这方面oknwwptz2#
从…起https://developer.mozilla.org/en-us/docs/web/api/urlsearchparams
The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present.
因此,您应该只提供查询参数字符串。e、 g.如果您的window.location.href
然后您应该只传递查询参数urlsearchparams类,即
query=1&query_1=2&many_queries=3
hvvq6cgz3#
下面的函数将从url返回所有参数的数组
引用自https://stackoverflow.com/a/20097994/8077687