[英]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.