javascript 从 url 中检索特定哈希标签的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3729150/
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-10-25 02:03:50  来源:igfitidea点击:

Retrieve specific hash tag's value from url

javascripthashtag

提问by mike

In raw Javascript, how would one go about checking that a specific hash tag exists in a url, then grab the value?

在原始 Javascript 中,如何检查 url 中是否存在特定的哈希标签,然后获取该值?

Example: http://www.example.com/index.html#hashtag1=value1&#hashtag2=value2

示例:http: //www.example.com/index.html#hashtag1=value1&#hashtag2=value2

I want to be able to grab the value of either hashtag1or hashtag2.

我希望能够获取hashtag1hashtag2的值。

回答by Cristian Sanchez

    var HashSearch = new function () {
       var params;

       this.set = function (key, value) {
          params[key] = value;
          this.push();
       };

       this.remove = function (key, value) {
          delete params[key];
          this.push();
       };


       this.get = function (key, value) {
           return params[key];
       };

       this.keyExists = function (key) {
           return params.hasOwnProperty(key);
       };

       this.push= function () {
           var hashBuilder = [], key, value;

           for(key in params) if (params.hasOwnProperty(key)) {
               key = escape(key), value = escape(params[key]); // escape(undefined) == "undefined"
               hashBuilder.push(key + ( (value !== "undefined") ? '=' + value : "" ));
           }

           window.location.hash = hashBuilder.join("&");
       };

       (this.load = function () {
           params = {}
           var hashStr = window.location.hash, hashArray, keyVal
           hashStr = hashStr.substring(1, hashStr.length);
           hashArray = hashStr.split('&');

           for(var i = 0; i < hashArray.length; i++) {
               keyVal = hashArray[i].split('=');
               params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
           }
       })();
    }

Using it:

使用它

Check if a "hash key" is present:

检查是否存在“哈希键”:

 HashSearch.keyExists("thekey");

Get the value for a hash key:

获取哈希键的值:

 HashSearch.get('thekey');

Set the value for a hash key, and update the URL hash:

设置哈希键的值,并更新 URL 哈希:

 HashSearch.set('thekey', 'hey');

Remove a hash key from the URL:

从 URL 中删除哈希键:

 HashSearch.remove('thekey');

Reload the hash into the local object:

将哈希重新加载到本地对象中:

 HashSearch.load();

Push the current key value set to the URL hash:

将当前设置的键值推送到 URL 哈希:

 HashSearch.push();

Note that when a key does not exist and you try to getit, it will returned undefined. However, a key could exist with no value -- for example #key=val&novaluewhere novalue is a key with no value. If you do HashSearch.get("novalue")it would also return undefined. In which case, you should use HashSearch.keyExists("novalue")to verify that it is indeed a key.

请注意,当密钥不存在而您尝试使用get它时,它将返回undefined. 但是,键可以不带值存在——例如#key=val&novalue,novalue 是一个不带值的键。如果你这样做,HashSearch.get("novalue")它也会返回undefined。在这种情况下,您应该使用HashSearch.keyExists("novalue")来验证它确实是一个密钥。

回答by Peter

I use this, and it works just fine for me. It's a little adjusing to a line I picked up somewhere, I believe on SO.

我使用这个,它对我来说很好用。这有点适应我在某个地方捡到的一条线,我相信 SO。

getURLHashParameter : function(name) {

        return decodeURI(
            (RegExp('[#|&]' + name + '=' + '(.+?)(&|$)').exec(location.hash)||[,null])[1]
        );
    }, 

回答by palswim

window.location.hashshould give you what you want.

window.location.hash应该给你你想要的。

回答by cwd

jQuery BBQ(back button and query) leverages the HTML5 hashchange event to allow simple, yet powerful bookmarkable #hash history. In addition, jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods.

jQuery BBQ(后退按钮和查询)利用 HTML5 hashchange 事件来允许简单而强大的书签 #hash 历史记录。此外,jQuery BBQ 提供了完整的 .deparam() 方法,以及哈希状态管理和片段/查询字符串解析和合并实用程序方法。

In short: This library allows you to dynamically change a hash "query string" within your page and have the URL match. It also allows you to dynamically pull values and normalizes working with the "query string." Finally it will add the query strings into the history which allows the back button to function as a navigation between previous query hash values.

简而言之:该库允许您在页面中动态更改哈希“查询字符串”并使 URL 匹配。它还允许您动态提取值并规范化“查询字符串”的使用。最后,它会将查询字符串添加到历史记录中,这允许后退按钮用作先前查询哈希值之间的导航。

A good move for UX would be to check out a library like jQuery BBQ :)

用户体验的一个好举措是查看像 jQuery BBQ 这样的库 :)