【问题标题】:window.location.href is Redirecting but not getting URLwindow.location.href 正在重定向但未获取 URL
【发布时间】:2020-04-09 19:21:29
【问题描述】:

代码

<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);

标签: javascript html css variables window


【解决方案1】:

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

【讨论】:

  • 非常感谢。我使用了很多语言,每种语言的 Print 语句要么是 + 要么 ,所以很困惑。
【解决方案2】:

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

如果您要单独打印出x,您将获得该值,但在您的上下文中,不正确的连接是问题所在。

【讨论】:

  • 非常感谢。我使用了很多语言,每种语言的 Print 语句要么是 + 要么 ,所以很困惑。
【解决方案3】:

要在 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>

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2014-06-18
      • 2013-03-23
      • 2021-10-10
      • 2013-09-07
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多