Javascript 拆分并解析 window.location.hash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5646851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:15:19  来源:igfitidea点击:

Split and parse window.location.hash

javascript

提问by user948438237

I'm facing issues with splitting and parsing window.location.hash correctly.

我遇到了正确拆分和解析 window.location.hash 的问题。

First of all, we get few parameters in hash, ex:

首先,我们在哈希中得到几个参数,例如:

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

As you surely see it's been created for search. When user clicks on pagination link page is being reloaded with the hash. So far so good.

正如您肯定看到的那样,它是为搜索而创建的。当用户点击分页链接页面时,会重新加载哈希值。到现在为止还挺好。

I created function initialise() that is calling every time when there's hash in the URL:

我创建了函数 initialise() ,每次 URL 中有哈希值时都会调用该函数:

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 is almost working... When I choose all search params hash is being... cut. For unknown reason for me. I tried to use if( params.indexOf('loc') )instead of a[0] == "loc"without any luck.

Everythig 几乎都在工作......当我选择所有搜索参数时,哈希正在......削减。对我来说原因不明。我尝试使用if( params.indexOf('loc') )而不是a[0] == "loc"没有任何运气。

Could you lend me a hand?

你能帮我一把吗?

Edit
Of course, I was using var a = ... in the loop, it was only copy-paste error.

编辑
当然,我在循环中使用 var a = ... ,这只是复制粘贴错误。

回答by KooiInc

You don't need a loop, if it's only the value of locfrom the hash you're after. This should also work.

你不需要循环,如果它只是loc你所追求的哈希值。这也应该有效。

var lochash    = location.hash.substr(1),
    mylocation = lochash.substr(lochash.search(/(?<=^|&)loc=/))
                  .split('&')[0]
                  .split('=')[1];
if (mylocation) {
   locationList(myLocation);
}

Concerning the trunctating of the hash after a page reload: imho that isn't related to your loop.

关于页面重新加载后散列的截断:恕我直言,这与您的循环无关。

EditA more modern and more accurate approach:

编辑一种更现代、更准确的方法:

const result = document.querySelector("#result");
const hash2Obj = "loc=austria&mr=1&min=10&max=89"
      .split("&")
      .map(v => v.split("="))
      .reduce( (pre, [key, value]) => ({ ...pre, [key]: value }), {} );
          

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

回答by sting

This should be a rather simpler way to read from location.hash:

这应该是一种从 location.hash 读取的更简单的方法:

    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

and then, you could use

然后,你可以使用

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

and other params that are available inside the hash

以及散列中可用的其他参数

回答by paulslater19

If you're using jQuery, check out the jQuery BBQ plugin

如果您使用 jQuery,请查看jQuery BBQ 插件

It "leverages the HTML5 hashchange event", which basically allows you to execute JavaScript code once the hash has been changed.

它“利用 HTML5 hashchange 事件”,它基本上允许您在哈希更改后执行 JavaScript 代码。

Furthemore, it comes with a powerful "depram" function, which allows you to "Parse the query string from a URL or the current window.location, deserializing it into an object, optionally coercing numbers, booleans, null and undefined values."

此外,它还带有一个强大的“ depram”功能,它允许您“从 URL 或当前 window.location 解析查询字符串,将其反序列化为对象,可选择强制数字、布尔值、空值和未定义值”。

回答by detaylor

params.indexOf('loc')will not return a value as locdoes not exist within the paramsarray. The item that you are looking for in the example provided is loc=austria. If you are only selecting by the key then you would need some looping to examine each key-value pair.

params.indexOf('loc')不会返回数组loc中不存在的值params。您在提供的示例中查找的项目是loc=austria。如果您仅通过键进行选择,那么您将需要一些循环来检查每个键值对。