[英]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>
我没有 function 或任何东西。 我只是在我的 HTML 文件中运行这个脚本代码,它曾经工作了几个月。 我不知道为什么它现在不起作用。 我如何能够使用window.location.href重定向页面但无法获得当前的 URL?
而不是alert("X: ",x);
尝试使用alert("X: " + x);
. 这应该解决它。 当您在警报 function 中放置逗号时,它可能会将其视为另一个参数,因此您必须使用“+”连接。
您需要使用+
将两个值正确连接在一起,而不是逗号,这只是将x
变量连接到打印。
如果您要自己打印出x
,您将获得该值,但在您的上下文中,不正确的连接是问题所在。
要将 append 一个字符串转换为 javascript 中的另一个字符串,应使用+
运算符。 您不能使用逗号。 仅当您使用需要多个参数的 function 时才使用它。
因为在这里, 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.