window.location.href 正在重定向但未获得 URL

window.location.href is Redirecting but not getting 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?

尝试使用 alert("X : " + x); 而不是 alert("X : ",x);。这应该解决它。当您在 alert 函数中放置一个逗号时,它可能会将其视为另一个参数,因此您必须使用“+”进行连接。

您需要使用 + 而不是逗号来正确地将两个值连接在一起,这只是将 x 变量连接到打印。

如果您要单独打印 x,您会得到该值,但在您的上下文中,错误的连接是问题所在。

要将一个字符串附加到 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>

已将 var 更改为 const。 请参阅有关串联的其他答案。更改为模板文字。

<script>
    // window.location.href = 'SomeSite.php'; // THIS WORKS
    alert(window.location.href);
    const x = window.location.href;
    alert(`x: ${x}`)
</script>