JavaScript 窗口.位置不起作用

javascript window.location not working

本文关键字:不起作用 位置 窗口 JavaScript      更新时间:2023-09-26

我是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。

任何帮助将不胜感激。

您没有提供协议,因此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

执行下列操作之一

  • 提供一个协议,以便它知道它是一个绝对的 URI,

    window.location = window.location.prototcol + '//' + window.location.host + window.location.pathname + '?foo=bar';
    
  • 告诉它重用当前协议,但作为绝对 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';
    

如果您需要调试,请始终选择最简单的选项来使您的生活更轻松,即,如果您可以假设您始终需要相同的协议、主机和路径,只需更新查询即可。


有用的知识

以 .. 开头的网址。

  • //表示相同的协议
  • /表示同源
  • ?表示相同的路径
  • #表示相同的查询(不会重新加载(
pathname 将是

类似于 /questions/35254564/javascript-window-location-not-working 的东西,而host是类似于 stackoverflow.com 的东西。如果你把它们和像你这样的代码放在一起,你会得到

stackoverflow.com/questions/35254564/javascript-window-location-not-working

这显然是不正确的;主机看起来像路径名的一部分。如果您真的觉得需要从其组成部分重建 URL,则可以使用 protocolport,但是如果您只想添加查询字符串,则使用 href 似乎更简单。