简体   繁体   English

使用两个可用的 href 更改活动导航栏链接的颜色

[英]Change color of active navbar link with two hrefs available

I can go on the START page when I have '/' and '/start' hrefs.当我有 '/' 和 '/start' href 时,我可以在 START 页面上显示 go。 But my JS function, which change my active link color works only on '/start' link but when it's '/' I have my page opened but my link on navbar isn't colored.但是我的 JS function,它改变了我的活动链接颜色只适用于“/开始”链接,但是当它是“/”时,我打开了我的页面,但我在导航栏上的链接没有颜色。 What should I do?我应该怎么办? Two links in html? html 中的两个链接? Or change my JS function?还是换我的JS function?

js: js:

function markActiveMenuItem() {
  var path = window.location.pathname;
  if (path != "/building" && !path.startsWith("/watch")) {
    $(".nav-link").each(function () {
      var href = $(this).attr("href");
      if (path.substring(0, href.length) === href) {
        $(this).addClass("active");
      }
    });
    $(".dropdown-item").each(function () {
      var href = $(this).attr("href");
      if (path.substring(0, href.length) === href) {
        $(this).closest(".nav-item").children("a").addClass("active");
      }
    });
  }
}

html: html:

    <li class="nav-item">
            <a class="nav-link" href="/start"> START </a>
        </li>

@Configuration class @配置class

  @GetMapping({"/", "/start"})
public String home(Model model) {
    return "templates/home";
}

Do you have a link with an href of / ?你有一个 href 为/的链接吗?

The path should be / (per your question), and you're comparing that to every nav-link's href路径应该是/ (根据您的问题),并且您正在将其与每个导航链接的 href 进行比较

$(".nav-link").each(function () {
    var href = $(this).attr("href");

Right here, presumably path is /在这里,大概路径是/

(path.substring(0, href.length) === href)

You'll never get a match if you don't have a nav-link with / as an href.如果您没有将/作为 href 的导航链接,您将永远无法匹配。

There's not enough info in your question to know.您的问题中没有足够的信息可以知道。 (Unless it's in the @GetMapping part; I don't know how that works.) (除非它在@GetMapping部分;我不知道它是如何工作的。)

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

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