javascript - 为相似的 url 添加基于 URL 的事件导航类

标签 javascript jquery laravel bootstrap-4 navigation

我正在尝试在导航中添加事件类。 我用过这篇文章。 Add Active Navigation Class Based on URL

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

效果很好。 但我的问题是在这种情况下。

/blog, /blogAds

如果 url 为 /blog, 事件类将添加到两个导航项。 有什么解决办法吗?

最佳答案

试试这个

if( new RegExp(location.pathname + "$").test( $this.attr('href') ) ) {
    $this.addClass('active');
}

测试使用:

new RegExp('\/blog$').test('/blogAds'); // returns false
new RegExp('\/blog$').test('/blog'); // returns true

Reference

关于javascript - 为相似的 url 添加基于 URL 的事件导航类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026162/

相关文章:

Laravel 查询构建器与 Raw

php - Laravel 中某个字段出现次数最多的查询

javascript - 单击禁用的按钮元素时,onblur 事件不会在 Chrome 中触发 - 在 IE 中有效

javascript - 无法将隐藏的表单值获取到 javascript 变量中

jquery - 在鼠标悬停时添加边框会移动内容

javascript - Darkroomjs 图像裁剪发布到 PHP

javascript - 从 Highcharts 获取图像 PHP Laravel

javascript - 如何将一个值推到值组合框中的最后一个值

javascript - 具有两个以上值的 HTML5 LocalStorage

javascript - jQuery-UI 的自动完成显示不佳,z-index 问题