简体   繁体   English

当页面刷新 jQuery 时,活动类被删除

[英]active class is removed when page refreshes jQuery

I have a UL on my page which is acting as navigation.我的页面上有一个用作导航的 UL。 In my footer I have some jQuery code so when I click the link it removes the active class on the li and then places it on the current li that has been clicked.在我的页脚中,我有一些 jQuery 代码,因此当我单击链接时,它会删除 li 上的活动类,然后将其放在已单击的当前 li 上。 This works as I click however when the page reloads the active class goes back onto the previous li.这在我单击时起作用,但是当页面重新加载时,活动类返回到前一个 li。

Here is my code这是我的代码

 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"); }); });
 <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>

Am I missing something in my jQuery to keep the class on the desired li?我是否在我的 jQuery 中遗漏了一些东西来使类保持在所需的 li 上?

Your JS is losing context with the refresh.您的 JS 因刷新而丢失上下文。

What you can do is run another function on load to check which url you're on, and set active state based on that.您可以做的是在加载时运行另一个函数来检查您所在的网址,并根据它设置活动状态。 Something like this:像这样的东西:

var setDefaultActive = function() {
    var path = window.location.pathname;

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

    element.addClass("active");
}

setDefaultActive()

My solution is based on this link .我的解决方案基于此链接 I needed nav pills to remain active after page refresh.我需要导航药丸在页面刷新后保持活动状态。 You can probably format this to fit your needs.您可以格式化它以满足您的需求。

$(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();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM