页面刷新/引导后保留打开选项卡

时间:2017-03-22 10:10:44

标签: javascript jquery html twitter-bootstrap

我有这个代码,在两个标签中显示两个菜单,如何在页面刷新后停止当前打开的标签重置?

<script type="text/javascript">
                            $(document).ready(function(){
                                $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
                                    localStorage.setItem('activeTab', $(e.target).attr('href'));
                                });
                                var activeTab = localStorage.getItem('activeTab');
                                if(activeTab){
                                    $('#subtabs a[href="' + activeTab + '"]').tab('show');
                                }
                            });
                            </script>

                        <ul id="subtabs" class="nav nav-tabs" role="tablist">
                            <li role="presentation" class="active"><a href="#artists" aria-controls="artists" role="tab" data-toggle="tab">Artists</a></li>
                            <li role="presentation"><a href="#subjects" aria-controls="subjects" role="tab" data-toggle="tab">Subjects</a></li>
                        </ul>

                        <div class="tab-content">
                            <div role="tabpanel" class="tab-pane active" id="artists">
                                <ul> 
                                <?php $loop = new WP_Query(array( 'post_type' => 'artist', 'posts_per_page' => -1 )) ; while ($loop->have_posts()) : $loop->the_post(); ?>

                                    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

                                <?php endwhile; ?>
                                </ul>
                            </div>
                            <div role="tabpanel" class="tab-pane" id="subjects">
                                <ul>
                                <?php $tax_terms = get_terms('subject');

                                    foreach($tax_terms as $term) {

                                        $term_link = get_term_link($term);

                                        if (is_wp_error($term_link)) {
                                            continue;
                                        } ?>

                                        <li><a href="<?php echo esc_url($term_link); ?>"><?php echo $term->name; ?></a></li>   

                                <?php } ?>
                                </ul>
                            </div>
                        </div>

1 个答案:

答案 0 :(得分:2)

实现这一目标的最简单方法是使用localStorage。每次单击选项卡列表时,只需将其添加到localstorage,然后在重新加载时将该项和该特定类添加到该特定选项卡中,以使其处于活动状态。

以下是来自tutorialrepublic的链接:http://www.tutorialrepublic.com/codelab.php?topic=faq&file=bootstrap-keep-last-selected-tab-active-on-page-refresh