【问题标题】:window.location.href with # hash after the .htmlwindow.location.href 在 .html 之后带有 # 哈希
【发布时间】:2017-02-15 20:57:05
【问题描述】:

我正在使用 window.location.href 来获取插入 jquery 的 url 路径。

它工作得很好,但现在我需要另辟蹊径,但我不知道该怎么做。

在我需要获取此 URL user.html 并插入活动类之前

这样做:

$(document).ready(function(){
    var loc = window.location.href; // returns the full URL

    if(/user/.test(loc)) {
        $('ul.nav.nav-tabs li').addClass('active');

    }
});

现在我需要这个:user.html#/details

如何使用下面的代码获取此网址:user.html#/details

$(document).ready(function(){
    var loc = window.location.href; // returns the full URL

    if(/user/.test(loc)) {
        $('ul.nav.nav-tabs li').addClass('active');

    }
});

【问题讨论】:

  • 你所说的“抓住”是什么意思?你到底想做什么?
  • 真的不知道你要做什么,但如果你想使用锚détails那么你不需要添加斜线,只需使用user.html#details
  • 如果 url 有:user.html#/details 插入活动的类,如果我得到 user.html 我可以这样做,但如果我得到 user.html#/details 就不能这样做
  • 你试过window.location.hash 吗?这将返回 URL 的 #/details 部分,您还可以将它与以下事件侦听器结合使用:window.addEventListener("hashchange", callbackFunction)

标签: javascript jquery


【解决方案1】:

您可以使用以下代码实现哈希检查:

$( document ).ready(
    function () {
        // Get the current URL
        var loc = window.location.href;
        // Get the hash part
        var hash = window.location.hash.replace( '#', '' );

        if ( 
            // If the location contains the word user
            /user/.test( loc ) &&
            // and the hash string has length greater than 0
            0 < hash.length &&
            // and the hash contains the string /details
            /\/details/.test( hash )
        ) {
            // Do stuff related to user page
            // with the details hash part
        }
    }
);

另外,如果你想让它更复杂,你可以有以下代码:

(function( $, window, undefined ) {

    // Handle the page elements related to the hash parts
    var track_hash_changes = function track_hash_changes() {
        // Get the current URL
        var loc = window.location.href;
        // Get the hash part
        var hash = window.location.hash.replace( '#', '' );

        if ( 
            // If the location contains the word user
            /user/.test( loc )
        ) {
            switch( hash ) {
                case '/case-1':
                    // Do stuff for case #1
                    break;
                case '/case-2':
                    // Do stuff for case #2
                    break;
                case '/case-X':
                    // Do stuff for case #X
                    break;
            }
        }
    };

    $( document ).ready(
        function () {
            // Listen for changes in the Hash part of the URL
            window.addEventListener("hashchange", track_hash_changes, false);
        }
    );
})( jQuery, this );

其中case-1case-2case-Xuser.html#/case-1user.html#/case-2user.html#/case-X

【讨论】:

  • 谢谢我可以申请不同的哈希? #/details, #/contact, #/email ?
  • 如果您对我分享的内容感到满意,请记住将我的答案标记为正确答案并投票 ;) :) 谢谢
  • 你也可以应用我已经更新的最终代码。这也将代码与全局命名空间隔离开来。
【解决方案2】:

window.location.href 应该继续得到你想要的。

如果您想了解某项工作的原理,只需将其输入控制台即可查看它包含哪些属性。例如,我刚刚在此页面的路径中添加了#/splurge,在控制台中输入了window.location,得到了以下信息:

【讨论】:

    【解决方案3】:

    您只需要为您的网址的详细信息变体编写正则表达式。

    /user\.html#\/details/

    如果您使用 if else 或 case 语句检查是否匹配,请确保将最具体的测试放在首位。

    编辑

    我会稍微修改一下以拥有不同的路线。

    使用带有哈希键和回调的对象,您可以自己创建一个不依赖正则表达式的简单路由器。

    很遗憾,该示例将不再有效,但可以在生产环境中使用。

    function router(loc) {
      return function(e) {
        var href = loc.href;
      
        var routes = {
          '/details': function() { console.log('details route') },
          '/contact': function() { console.log('contact route') },
          '/email': function() { console.log('email route') },
          'default': function() { console.log('no hash set') }
        }
      
        if (/user\.html/.test(loc.href)) {
          if (typeof routes[loc.hash] === 'function') {
            return routes[loc.hash]()
          }
          return routes['default']()
        }
      }
    }
    
    var mockLocation = {
      hash: '/contact',
      href: 'user.html#/contact'
    }
    
    // bind the router to page load and hash change.
    // change mockLocation to window.location for production
    $(document).on('ready', router(mockLocation))
    $(window).on('hashchange', router(mockLocation))
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 谢谢我可以申请不同的哈希? #/details, #/contact, #/email ?
    猜你喜欢
    • 1970-01-01
    • 2010-10-14
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多