2012-07-30 94 views
5

我有這樣http://www.example.com/folder/file.html#val=90&type="test"&set="none"&value="reset?setvalue=1&setvalue=45"如何在Javascript中獲取網址的hashtag值和&符號值?

現在我需要從開始#得到URL部分URL時,如何獲取,我嘗試使用window.location.search.substr();但看起來像搜索?在一個網址。是那裏得到URL的值#

如何我也從符號得到URL的一部分&

感謝後, 邁克爾

+0

好運@Mike? – 2012-07-30 18:59:44

+0

@MatthewBlancarte沒有任何捷徑獲取任何東西后,像我們有什麼散列標籤,如果不是那麼是什麼方法 – Mike 2012-07-30 19:06:33

+0

你有沒有嘗試在我的答案的底部的接受的方法? http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript這將解析查詢字符串。如果你在做這個服務器端(例如PHP/Rails /等),它會簡單得多。 – 2012-07-30 19:22:47

回答

13
var hash = window.location.hash; 

這裏更多的信息的方法:https://developer.mozilla.org/en/DOM/window.location

更新:這將抓取hashtag之後的所有字符,包括任何查詢字符串。從MOZ手冊:

window.location.hash === the part of the URL that follows the # symbol, including the # symbol. 
You can listen for the hashchange event to get notified of changes to the hash in 
supporting browsers. 

現在,如果你需要分析查詢字符串,我相信你做的,在這裏檢查了這一點:How can I get query string values in JavaScript?

+0

還有一種方法可以在& – Mike 2012-07-30 18:32:08

+0

之後得到一個值 - 這是一個單獨的問題 - 請將其張貼,或編輯當前問題。 '?'後面的部分(不是'&'是查詢字符串 - 你問過散列)。 – Utkanos 2012-07-30 18:33:01

+0

@Utkanos我現在編輯請回答如果你知道 – Mike 2012-07-30 18:36:48

0

這將得到#&值:

var page_url = window.location + "";  // Get window location and convert to string by adding "" 
var hash_value = page_url.match("#(.*)"); // Regular expression to match anything in the URL that follows # 
var amps;         // Create variable amps to hold ampersand array 

if(hash_value)        // Check whether the search succeeded in finding something after the # 
{ 
    amps = (hash_value[1]).split("&");  // Split string into array using "&" as delimiter 
    alert(amps);       // Alert array which will contain value after # at index 0, and values after each & as subsequent indices 
} 
+0

無法讀取null的屬性'1'是我在控制檯中運行時得到的錯誤 – Mike 2012-07-30 18:40:54

+1

這會在任何時候沒有散列時出錯,因爲假定匹配,沒有檢查。 – Utkanos 2012-07-30 18:45:38

+0

能否請你解釋你的第二行代碼 – Mike 2012-07-30 18:52:55

5

搶哈希:

location.hash.substr(1); //substr removes the leading # 

爲了克饒查詢字符串

location.search.substr(1); //substr removes the leading ? 

[編輯 - 因爲你似乎有幾分查詢字符串彼岸字符串,它實際上是你的哈希值的部分,下面將檢索並解析爲名稱的對象/值配對。

var params_tmp = location.hash.substr(1).split('&'), 
    params = {}; 
params_tmp.forEach(function(val) { 
    var splitter = val.split('='); 
    params[splitter[0]] = splitter[1]; 
}); 
console.log(params.set); //"none" 
+0

location.search.substr(1);似乎不適合我。 – Mike 2012-07-30 18:48:00

+0

這是因爲您將查詢字符串與哈希混淆。你似乎有一種查詢字符串esq字符串作爲你的散列的一部分。如果你想提取那*你需要一些REGEX,字符串處理。我會編輯答案。 – Utkanos 2012-07-30 18:49:59