jquery 如何根据当前URL将.active类添加到菜单< a>标签中?

x33g5p2x  于 2023-04-20  发布在  jQuery
关注(0)|答案(2)|浏览(126)

我正在为我的网站创建一个自定义菜单。我想在这里添加一个活动类,以便在菜单项与当前页面链接匹配时突出显示它。
例如:如果用户在页面https://mywebsite.it/explore-docs上,则.link_expdocs获得活动类。
我设法用一些Javascript做到了这一点,但我不喜欢出来的东西。我已经迭代了很多次代码,我不认为这是一个好的做法。
有没有更好更短的实践,这样我就不会每次都重复相同的代码,也不必显式地编写indexOf中的所有类和slug?
对不起,但我是新来的,我是通过在stackoverflow上四处寻找来做到这一点的。
我试图缩短的代码(不工作):
我试着这样缩短代码,但即使在其他页面上,活动类也总是被添加到.link_home中,当URL中存在/account slug时,link_dashboard也会发生同样的情况

document.addEventListener("DOMContentLoaded", function() {
  const links = document.querySelectorAll(".item_menu a");

  links.forEach(link => {
    if (window.location.href.indexOf(link.getAttribute("href")) > -1) {
      link.classList.add('active');
    }
  });
});

原始代码(工作):

<!-- Vertical Navigation -->
<div class="vertical_nav">

  <!-- User Menu -->
  <div class="user_menu">
    <div class="wrap_user_navigation">
      <div class="user_navigation">
        <div class="item_menu">
          <a class="link_dashboard" href="https://mywebsite.it/account">Dashboard</a>
        </div>

        <div class="item_menu">
          <a class="link_ordini" href="https://mywebsite.it/orders">I miei ordini</a>
        </div>

        <div class="item_menu">
          <a class="link_downloads" href="https://mywebsite.it/downloads">Libreria Downloads</a>
        </div>

        <div class="item_menu">
          <a class="link_settings" href="https://mywebsite.it/settings">Impostazioni</a>
        </div>
      </div>  
    </div>  
  </div>

  <div class="main_menu">
    <div class="item_menu">
      <a class="link_home" href="https://mywebsite.it/">Home</a>
    </div>  

    <div class="item_menu">
      <a class="link_expdocs" href="https://mywebsite.it/explore-docs">Explore Docs</a>
    </div> 

    <div class="item_menu">
      <a class="link_coaching" href="https://mywebsite.it/services">Online Coaching</a>
    </div> 

    <div class="item_menu">
      <a class="link_calculator" href="https://mywebsite.it/math">Fitness Calculator</a>
    </div> 
  </div>

  <!-- Docs Menu -->
  <div class="doc_menu">
    <div class="item_menu">
      <a class="link_anadocs" href="https://mywebsite.it/docs-anatomy">Docs Anatomy</a>
    </div> 

    <div class="item_menu">
      <a class="link_evidence" href="https://mywebsite.it/evidence-based">Evidence Based</a>
    </div> 

    <div class="item_menu">
      <a class="link_strengthvalue" href="https://mywebsite.it/strength-value">Strength Value</a>
    </div> 

    <div class="item_menu">
      <a class="link_mission" href="https://mywebsite.it/mission">Mission</a>
    </div> 
  </div>

  <!-- Footer Items -->
  <div class="footer_menu">
    <div class="item_menu">
      <a class="link_support" href="https://mywebsite.it/supporto">Supporto</a>
    </div> 

    <div class="item_menu">
      <a class="link_logout" href="https://mywebsite.it/wp-login.php?action=logout">Logout</a>
    </div> 
  </div>

</div>
document.addEventListener("DOMContentLoaded", function() {

  // Add - Remove class active for user_menu
  if(window.location.href.indexOf("account") > -1) {
    document.querySelector(".link_dashboard").classList.add('active');
  } 
  if(window.location.href.indexOf("orders") > -1) {
    document.querySelector(".link_ordini").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  }   
  if(window.location.href.indexOf("downloads") > -1) {
    document.querySelector(".link_downloads").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 
  if(window.location.href.indexOf("settings") > -1) {
    document.querySelector(".link_settings").classList.add('active');
    document.querySelector(".link_dashboard").classList.remove('active');
  } 

  // Add - Remove class active for main_menu
  if(window.location.href === "https://mywebsite.it/") {
    document.querySelector(".link_home").classList.add('active');
  }
  if(window.location.href.indexOf("explore-docs") > -1) {
    document.querySelector(".link_expdocs").classList.add('active');
  }   
  if(window.location.href.indexOf("services") > -1) {
    document.querySelector(".link_coaching").classList.add('active');
  } 
  if(window.location.href.indexOf("math") > -1) {
    document.querySelector(".link_calculator").classList.add('active');
  }

  // Add - Remove class active for doc_menu
  if(window.location.href.indexOf("docs-anatomy") > -1) {
    document.querySelector(".link_anadocs").classList.add('active');
  } 
  if(window.location.href.indexOf("evidence-based") > -1) {
    document.querySelector(".link_evidence").classList.add('active');
  }   
  if(window.location.href.indexOf("strength-value") > -1) {
    document.querySelector(".link_strengthvalue").classList.add('active');
  } 
  if(window.location.href.indexOf("mission") > -1) {
    document.querySelector(".link_mission").classList.add('active');
  }
});
hgtggwj0

hgtggwj01#

你需要得到url的确切部分来进行比较。为此,我们可以用/分割href,这样就可以创建数组,反转数组并获取第一个元素。

document.addEventListener("DOMContentLoaded", function() {
  const links = document.querySelectorAll(".item_menu a");

  links.forEach(link => {
    /*let slug = link.getAttribute("href").split("/").reverse()[0];
    if (window.location.href.indexOf(slug) > -1) {
      link.classList.add('active');
    }*/

    if (window.location.href === link.getAttribute("href")) {
      link.classList.add('active');
    }
  });
});
wb1gzix0

wb1gzix02#

感谢@CodeThing的回答,我找到了这个对我有效的解决方案。

// Get url current page
var currentUrl = window.location.href;

// Remove slash ("/") from the current page's URL
if (currentUrl.slice(-1) === "/") {
  currentUrl = currentUrl.slice(0, -1);
}

// Select all <a> tags in the vertical menu
var menuLinks = document.querySelectorAll('.vertical_nav a');

// Iterate through all the links in the menu and add class "active" if the URL of the link matches the URL of the current page
menuLinks.forEach(function(link) {
  var linkUrl = link.href;

  // Remove slash ("/") from the current page's URL
  if (linkUrl.slice(-1) === "/") {
    linkUrl = linkUrl.slice(0, -1);
  }

  if (linkUrl === currentUrl) {
    link.classList.add('active');
  }
});

相关问题