簡體   English   中英

Javascript:如何將變量附加到網址?

[英]Javascript: how can I append variables to the url?

如何在不導航到URL的情況下使用javascript將變量附加到URL?

謝謝

要將變量附加到散列(如Matthew建議的那樣 ),您可以在純JavaScript中執行以下操作:

window.location.hash = 'varA=some_value;varB=some_value';

這會將#varA=some_value;varB=some_value到您的URL。 除非哈希值等於文檔中的錨名稱或元素id,否則它不會刷新頁面。

然后檢查是否存在哈希值,只需執行以下操作:

var i, variables = window.location.hash.split(';');

if (variables.length > 0) {
    // Variables present in hash
    for (i = 0; i < variables.length; i++) {
       keyValuePair = variables.split('=');
       // keyValuePair[0] would be the key (variable name)
       // keyValuePair[1] would be the value
    }
}
else {
    // No variables in the hash
}

您可能還想查看以下Stack Overflow帖子,了解與不同瀏覽器中哈希部分的URL編碼相關的問題:

您可以修改window.location.hash 其他任何東西都會導致導航。

我不確定,但這是怎么回事?:

document.url + myVar + 'myString';

雖然Javascript不是我的語言:P

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM