我是 javascript 新手,并陷入了这个问题。我试图根据选中的复选框更改 url 查询字符串。但我似乎对 window.location 有一些问题,一些 JavaScript 如下
var urltest= window.location.pathname;
var urltest2 = window.location.host;
var currentURL = urltest2 + urltest;
url = currentURL + "?" + arr_opts.join('&');
document.getElementById('myurl').innerHTML = url;
//window.location.href = url;
window.location = url;
window.location 在这里不起作用,但是当我将 var currentURL 更改为
var currentURLL = window.location.href;
这是工作,但不是
var urltest= window.location.pathname;
var urltest2 = window.location.host;
var currentURL = urltest2 + urltest;
我需要 window.location 将页面指向上面的当前 URL。
如有任何帮助,我们将不胜感激。
最佳答案
您没有提供协议(protocol),因此 location.href
更改被视为“从当前位置转到此相对路径”,即在此页面上
window.location = window.location.host + window.location.pathname;
// takes us to
// http://stackoverflow.com/questions/35254564/javascript-window-location-not-working/stackoverflow.com/questions/35254564/javascript-window-location-not-working/35254601
执行以下操作之一
提供一个协议(protocol),以便它知道它是一个绝对 URI,
window.location = window.location.prototcol + '//' + window.location.host + window.location.pathname + '?foo=bar';
告诉它重新使用当前协议(protocol),但作为绝对 URI 工作
window.location = '//' + window.location.host + window.location.pathname + '?foo=bar';
提供来源(而不是主机)
window.location = window.location.origin + window.location.pathname + '?foo=bar';
告诉它重新使用相同的原点,但作为绝对路径工作
window.location = window.location.pathname + '?foo=bar';
只需更新查询
window.location = '?foo=bar';
如果您需要调试,请始终选择最简单的选项,以使您的生活更轻松,即,如果您可以假设您始终需要相同的协议(protocol)、主机和路径,则只需更新查询即可。
<小时/>有用的知识
以 .. 开头的 URL
//
表示相同协议(protocol)/
表示同源?
表示相同路径#
表示相同的查询(不会重新加载)
关于javascript window.location 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254564/