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

发布于 2024-09-24 05:15:44 字数 313 浏览 0 评论 0原文

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

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

我希望能够获取 hashtag1hashtag2 的值。

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

故事未完 2024-10-01 05:15:44
    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];
           }
       })();
    }

使用

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

 HashSearch.keyExists("thekey");

获取哈希键的值:

 HashSearch.get('thekey');

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

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

从 URL 中删除哈希键:

 HashSearch.remove('thekey');

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

 HashSearch.load();

将当前键值集推送到 URL 哈希值:

 HashSearch.push();

请注意,当某个键不存在并且您尝试获取它时,它将返回未定义.但是,键可能没有值,例如 #key=val&novalue,其中 novalue 是没有值的键。如果您执行HashSearch.get("novalue"),它也会返回undefined。在这种情况下,您应该使用 HashSearch.keyExists("novalue") 来验证它确实是一个键。

    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:

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

Remove a hash key from the URL:

 HashSearch.remove('thekey');

Reload the hash into the local object:

 HashSearch.load();

Push the current key value set to the URL hash:

 HashSearch.push();

Note that when a key does not exist and you try to get it, it will returned undefined. However, a key could exist with no value -- for example #key=val&novalue where 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.

狠疯拽 2024-10-01 05:15:44

我用这个,它对我来说效果很好。我相信这是对我在某处拾取的一句台词的一点调整。

getURLHashParameter : function(name) {

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

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.

getURLHashParameter : function(name) {

        return decodeURI(
            (RegExp('[#|&]' + name + '=' + '(.+?)(&|$)').exec(location.hash)||[,null])[1]
        );
    }, 
躲猫猫 2024-10-01 05:15:44

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

window.location.hash should give you what you want.

离鸿 2024-10-01 05:15:44

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

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

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

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.

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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文