jQuery和Bootstrap集成

时间:2018-11-24 04:12:03

标签: jquery twitter-bootstrap

我试图找到如何在加载页面时添加活动类。由于某种原因,这在我的代码中不起作用:

<nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top">
  <div class="container">
    <a class="navbar-left" href="index.html"><img src="img/logo.png" /></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
            </li>

            <li class="nav-item">
                <a class="nav-link" href="#products">Products</a>
            </li>

            <li class="nav-item">
                <a class="nav-link" href="#about">About Us</a>
            </li>

            <li class="nav-item">
                <a class="nav-link" href="contact.html">Contact Me</a>
            </li>
        </ul>
    </div>
  </div>
</nav>

jQuery文件

$(document).ready(function () {
    var url = window.location;
    $('ul.nav a[href="'+ url +'"]').parent().addClass('active');
    $('ul.nav a').filter(function() {
        return this.href == url;
    }).parent().addClass('active');
});

主页上有一个小细节,我有section标签,但它们确实有各自的页面。 / products / aboutus等

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

$(document).ready(function ($) {
    var url = window.location.href;
    var activePage = url;
    $('.nav-item a').each(function () {
        var linkPage = this.href;

        if (activePage == linkPage) {
            $(this).closest("li").addClass("active");
        }
    });
});