首页 > 解决方案 > window.location.href 正在重定向但未获取 URL

问题描述

代码

<script>
  window.location.href = 'SomeSite.php';   // THIS WORKS
  var x = window.location.href;            // THIS DOES NOT!  
  alert("X : ",x);                         // Shows X : 
</script>

我没有任何功能或任何东西。我只是在我的 HTML 文件中运行这个脚本代码,它曾经工作了几个月。我不知道为什么它现在不起作用。我如何能够使用window.location.href重定向页面但无法获取当前 URL?

标签: javascripthtmlcssvariableswindow

解决方案


要将字符串附加到 javascript 中的另一个字符串,您应该使用+运算符。您不能使用逗号。仅当您使用需要多个参数的函数时才使用它。

因为在这里,alert()以为您要放置第二个参数!

例如:

let string1 = "Hello, "; //Define the first variable.
let string2 = "world!";  //And the second one.

alert(string1 + string2);//Show a message and join the two strings together!

在这里您可以使用逗号:

<script>
   let string = "We hate the earth!";
   string = string.replace("hate", "love"); //FYI: replace() is used to replace a sequence of characters by an another.
</script>

所以你的代码应该是:

<script>
  var x = window.location.href;
  alert("X : " + x);           //Join "X : " and x together!
</script>

推荐阅读