【问题标题】:import or including navbar into different file pages with dynamic active nav tab使用动态活动导航选项卡将导航栏导入或包含到不同的文件页面中
【发布时间】:2021-03-29 14:43:55
【问题描述】:

我只想问是否有办法将我的导航栏存储在一个文件页面中并根据用户点击的内容动态更改其活动状态?

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
  </div>
</nav>

与此代码一样,它将存储在一页中。但是如果单击功能并且功能应该是活动项目,则主页不应处于活动状态。因为我将相同的导航栏复制到每个页面中,并且更改其活动取决于文件页面。如果可能的话,我想这样做以避免冗余。谢谢。

【问题讨论】:

  • 我认为使用原始 HTML 无法实现,您需要使用 PHP/JS 来获取用户所在的当前页面,并在此基础上调整类以包含您需要的其他属性。
  • @Skully 你好,我搜索什么来通过 JS 实现这个?我真的不知道至少得到与我的问题相似的结果的关键字是什么。谢谢。
  • 使用window.location.pathname获取当前页面,如果href与路径匹配则添加类。
  • @AbhishekSarwan 所以基本上逻辑应该有一个条件,如果类被点击,那么我应该触发 window.location.pathname?这可以通过 JavaScript 来完成,对吗?如果我错了,请纠正我,谢谢。
  • 基本上是的,您只需查看当前文档 URL 并根据需要调整 HTML 元素以添加您的“(当前)”后缀。请参阅我的答案以了解如何做到这一点。

标签: html twitter-bootstrap


【解决方案1】:

您可以使用 Javascript 按类从导航栏中收集所有 &lt;a&gt; 元素,在这种情况下,您的 nav-link 类就可以了。通过这些链接的集合,我们可以遍历它们并检查哪个目标 href 与用户所在的当前页面匹配,并将文本附加到它的末尾。

您可以将以下代码块放在结束正文标记之前。

<script>
    $(document).ready(function() {
        let allLinks = $(".nav-link").map(function() {
            return this; // Fetch all elements that have the .nav-link class and add them to our list.
        }).get();

        // Iterate through each of the links we fetched.
        $.each(allLinks, function(key, value) {
            if (value.href == document.URL) { // If the href attribute for this link matches the current page URL.
                $(this).html(value.innerText + " <span class='sr-only'>(current)</span>"); // Adjust the HTML of the element and append a suffix to the end, or do anything else here as required.
            }
        });
    });
</script>

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 2018-10-28
相关资源
最近更新 更多