为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶刀刀 2023-12-04 17:12:47
代码<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?
查看完整描述

4 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

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



查看完整回答
反对 回复 2023-12-04
?
GCT1015

TA贡献1827条经验 获得超4个赞

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


<script>

    // window.location.href = 'SomeSite.php'; // THIS WORKS

    alert(window.location.href);

    const x = window.location.href;

    alert(`x: ${x}`)

</script>


查看完整回答
反对 回复 2023-12-04
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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


查看完整回答
反对 回复 2023-12-04
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

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

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


查看完整回答
反对 回复 2023-12-04
  • 4 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信