jquery 将 .active 添加到 Bootstrap 导航栏

标签 jquery css twitter-bootstrap

在根据浏览器 url 参数将 .active 类附加到 Bootstrap 导航栏元素时,我现有的 jQuery 存在一些问题。

问题是 index.php 将为匹配 index.php 的导航栏元素生成事件类,但是如果没有 index.php 存在,该元素将不会显示为事件的,传递查询时似乎会出现同样的问题。

例如 inbox.php 将生成 .active 类,而 inbox.php?view=sent 将不生成任何内容。

这是现有的 jQuery 有人可以帮我解决这个小问题 index.php 和/不显示 .active 以及包含同一页面查询参数的链接。

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

.nav 结构是默认的 Bootstrap 导航结构,没什么特别的。我曾尝试使用 PHP 来附加 .active 类,但由于某种原因它不想很好地发挥作用,我使用了在 StackOverflow 上找到的关于 PHP 和添加 .active 的 元素。

提前致谢。

最佳答案

假设您所有的页面都有类似于 .../myPage.ext?x=y 的路径, 其中ext是任何给定的页面扩展名,即 php, html, etc. ,以下代码片段获取当前页面,通过拆分 window.location 删除查询字符串(如果有)在'?'并获取当前页面的名称,然后搜索 nav-bar对于 <a></a>与匹配 href .与您正在做的非常相似。

<script>
    $(document).ready(function () {
        // Let's get rid of the query string
        var path = location.pathname.split('?')[0];
        var start = path.lastIndexOf('/');
        var activeLink = path.substr(start);

        var parent = $('a[href*="' + activeLink + '"]').parent('li');
        // These two lines check if you have dropdowns in your nav-bar
        if (parent.closest('ul').hasClass('dropdown-menu')) {
            parent.parents('.dropdown').addClass('active');
        }
        parent.addClass('active');
    });
</script>

关于jquery 将 .active 添加到 Bootstrap 导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40138065/

相关文章:

javascript - jQuery - 如何从表单提交 `post` `multipart/form-data` 并调用函数?

Jquery zoom with a clickable element that doesn't disrup the functionality

html - 将 X 像素添加到当前位置 CSS

html - 外部 CSS 文件无法获取类

javascript - 可拖动列表到 html5 表格中存在错误

javascript - 使用 indexOf 比较数组的第一个和下一个元素。 JavaScript

javascript - 使用 Jquery 单击时使链接加粗

html - 基本样式位令人惊讶地没有被应用

ruby-on-rails - 带有 simple_form 的按钮内的 HTML 代码

html - 如何在 Bootstrap 中对齐列内的控件?