2011-04-13 133 views
12

我正在面對拆分和解析window.location.hash問題。拆分和解析window.location.hash

首先,我們得到的哈希幾個參數,例如:

#loc=austria&mr=1&min=10&max=89 

正如你肯定會看到它被搜索創建。當用戶點擊分頁鏈接頁面正在重新加載散列。到現在爲止還挺好。

我創建功能INITIALISE()正在調用每當有在URL中的hash:

if (window.location.hash) { 
    var params = (window.location.hash.substr(1)).split("&"); 

    for (i = 0; i < params.length; i++) 
    { 
     var a = params[i].split("="); 
     // Now every parameter from the hash is beind handled this way 
     if (a[0] == "loc") 
     { 
      locationList(a[1]); 
     } 
    } 
} 

Everythig幾乎工作......當我選擇所有搜索PARAMS哈希正在...切。對於我來說不明原因。我試圖用if(params.indexOf('loc'))而不是a[0] == "loc"沒有任何運氣。

你能幫我一把嗎?

編輯
當然,我是用VAR一個= ...在循環,那也只是複製粘貼錯誤。

+0

*當我選擇所有搜索PARAMS哈希正在...切*。我不明白這句話...... – 2011-04-13 09:12:48

+0

當我重新加載頁面後,我有這樣的'#loc = austria&mr = 1&min = 10&max = 89'這樣的散列,它就是'#loc = austria&mr = 1'。 – user948438237 2011-04-13 09:17:02

+0

你有沒有試過'if(params [i] .indexOf('loc'))'? – 2011-04-13 09:32:45

回答

25

如果它只是您之後哈希的值loc,則不需要循環。這也應該起作用。

var lochash = location.hash.substr(1), 
    mylocation = lochash.substr(lochash.indexOf('loc=')) 
        .split('&')[0] 
        .split('=')[1]; 
if (mylocation) { 
    locationList(myLocation); 
} 

關於散列trunctating頁面重新加載後:恕我直言,這是不相關的循環。

編輯一個更現代,更準確的方法:

const result = document.querySelector("#result"); 
 
const hash2Obj = "loc=austria&mr=1&min=10&max=89" 
 
     .split("&") 
 
     .map(el => el.split("=")) 
 
     .reduce((pre, cur) => { pre[cur[0]] = cur[1]; return pre; }, {}); 
 

 
result.textContent += `loc => ${hash2Obj.loc} 
 
---- 
 
*hash2Obj (stringified): 
 
${JSON.stringify(hash2Obj, null, ' ')}`;
<pre id="result"></pre>

+0

你說得對。現在我意識到我有一個邏輯錯誤(即使哈希存在,也調用buildRequestHash()函數)。謝謝。 – user948438237 2011-04-13 09:33:57

+0

從技術上講,如果在值字符串中使用未轉義的'=',則會出現小錯誤...請考慮「#key1 = foo = bar,alloc = true&loc = ...」的情況。沒什麼大不了的,只是我碰到的東西。乾杯! – 2014-09-10 21:44:26

+0

也匹配'#bloc =東西' – Hugo 2016-12-06 20:46:14

0

params.indexOf('loc')將不會返回值,因爲loc不存在於params陣列中。您在提供的示例中查找的項目是loc=austria。如果你只是通過鍵選擇,那麼你需要一些循環來檢查每個鍵 - 值對。

1

如果你使用jQuery,檢查出jQuery BBQ plugin

它「充分利用了HTML5 hashchange事件「,它基本上允許您在散列更改後執行JavaScript代碼。

Furthemore,它帶有一個強大的「depram」功能,它可以讓你「從URL或當前window.location的解析查詢字符串,它反序列化到一個對象,可選脅迫數字,布爾值,null和undefined值「。

2

這應該是一個比較簡單的方式來讀取位置。哈希:

var hash = window.location.hash.substring(1); 
    var params = {} 
    hash.split('&').map(hk => { 
     let temp = hk.split('='); 
     params[temp[0]] = temp[1] 
    }); 
    console.log(params); //Here are the params to use 

,然後,你可以使用

params.access_token //access_token 
params.id //id 

等PARAMS可用的散列內