javascript window.location不工作

时间:2016-02-07 14:15:40

标签: javascript url

我是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将页面指向上面的currentURL。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您未提供协议,因此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';
    

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

有用的知识

使用..

启动网址
  • //表示相同协议
  • /表示同源
  • ?表示相同路径
  • #表示相同的查询(不会重新加载)

答案 1 :(得分:0)

pathname类似于/questions/35254564/javascript-window-location-not-workinghost类似于stackoverflow.com。如果你把这些与你的代码放在一起,你得到

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

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

相关问题