2011-04-13 136 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可用的散列内