【问题标题】:Keep selected tab when click on browser back button or mobile back button单击浏览器后退按钮或移动设备后退按钮时保留选定的选项卡
【发布时间】:2015-10-08 17:37:56
【问题描述】:

我在移动视图中使用下面的 html 代码作为标签

 <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
     $(document).ready(function(){
                $('a.tab-menu').click(function(){
                    if ( $(window).width() < 768 ) 
                   $('#tab-'+($('.tab-menu').index($(this))+1)).slideToggle("slow").siblings('div').hide('slow');
                });
            });
    </script>
    </head>

    <body>
    <h2 class="responsive-tab"><a href="#tab-1" class="tab-menu">tab 1</a></h2>
    <div id="tab-1"> content here </div>
    <h2 class="responsive-tab"><a href="#tab-2" class="tab-menu">tab 1</a></h2>
    <div id="tab-2"> content here </div>
    <h2 class="responsive-tab"><a href="#tab-3" class="tab-menu">tab 1</a></h2>
    <div id="tab-3"> <a href="#">link here</a> </div>
    </body>
    </html>

我的问题是,如果单击所选选项卡上的任何链接并转到链接,并且当我单击后退按钮应返回所选选项卡时,我如何保留所选选项卡

【问题讨论】:

    标签: javascript jquery jquery-ui jquery-plugins


    【解决方案1】:

    您可以在页面准备就绪时查看location.hash,然后在页面加载时触发对该选项卡的点击。

    $(function () {
      // Let's see if there's a hash in the url...
      var hash = location.hash;
    
      // If there is...
      if (hash) {
    
        //  Find the link that has the same href value
        // as the hash and fake a click on it...
        $('a').filter(function () {
          return this.href === hash;
        }).trigger('click');
      }
    });
    

    【讨论】:

    • 感谢您的回答,您的意思是 $(function () { var hash = location.hash; if (hash) { $('a.tab-menu').filter(function () { return this.href === hash; }).trigger('click'); } });
    • 感谢您的回答,您的意思是 $(function () { var hash = location.hash; if (hash) { $('a.tab-menu').filter(function () { return this.href === hash; }).trigger('click'); } });
    • 是的,你可以尽可能具体。
    • 对不起我不擅长 jQuery 那么代码将是 $(document).ready(function(){ $('a.tab-menu').click(function(){ if ( $(window).width()
    • 是的,看起来差不多。您可能想console.log(this.href, hash) 以确保它们在该过滤器函数中完全相同。
    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2019-09-13
    • 2023-03-05
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多