首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >页刷新jQuery时移除活动类。

页刷新jQuery时移除活动类。
EN

Stack Overflow用户
提问于 2017-01-24 08:11:09
回答 2查看 5.4K关注 0票数 0

我的页面上有一个UL,它充当导航。在我的页脚中,我有一些jQuery代码,所以当我单击该链接时,它会移除li上的活动类,然后将其放置在已单击的当前li上。但是,当页面重新加载时,活动类返回到以前的li时,这是可行的。

这是我的密码

代码语言:javascript
复制
 jQuery(document).ready(function () {

        "use strict";

        // Init Demo JS
        Demo.init();


        // Init Theme Core
        Core.init();

        $('.sidebar-menu > li').click(function (e) {
            $(".active").removeClass("active");
            $(this).addClass("active");
        });
    });
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav sidebar-menu">
            <li class="sidebar-label pt20">Menu</li>
            <li class="active">
                <a href="/dashboard">
                    <span class="glyphicon glyphicon-home"></span>
                    <span class="sidebar-title">Dashboard</span>
                </a>
            </li>
            <li>
                <a href="/fixtures">
                    <span class="fa fa-calendar"></span>
                    <span class="sidebar-title">Fixtures</span>
                </a>
            </li>
            <li>
                <a href="/players">
                    <span class="glyphicon glyphicon-book"></span>
                    <span class="sidebar-title">Players</span>
                </a>
            </li>
</ul>

我是否在jQuery中遗漏了一些东西,以使类保持在所需的li上?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-24 08:27:03

您的JS正在因为刷新而失去上下文。

您可以做的是在加载时运行另一个函数来检查您在哪个url上,并在此基础上设置活动状态。就像这样:

代码语言:javascript
复制
var setDefaultActive = function() {
    var path = window.location.pathname;

    var element = $(".sidebar-menu a[href='" + path + "']");

    element.addClass("active");
}

setDefaultActive()
票数 5
EN

Stack Overflow用户

发布于 2020-12-13 08:58:21

我的解决方案是基于此链接的。我需要导航药片在页面刷新后保持活跃。您可能可以将其格式化以满足您的需要。

代码语言:javascript
复制
$(document).ready(function () {
  // On page load
  $('a[data-toggle="pill"]').on('show.bs.tab', function (e) {
    // Get the id for the pill that was last shown and set it to local storage
    localStorage.setItem('activeLink', $(e.currentTarget).attr('id'));
  });
  // After page loaded
  // Get the id for the pill from local storage
  var activeLink = localStorage.getItem('activeLink');
  // If it's there, click it
  if (activeLink) {
    $(`#${activeLink}`).click();
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41823055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档