【问题标题】:Add Active Navigation Class Based On Url for similar url为类似的 url 添加基于 Url 的 Active Navigation 类
【发布时间】:2020-07-16 11:10:34
【问题描述】:

我正在尝试在导航中添加活动类。 我用了这篇文章。 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, 活动类添加到两个导航项。 有什么解决办法吗?

【问题讨论】:

    标签: javascript jquery laravel bootstrap-4 navigation


    【解决方案1】:

    试试这个

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2013-12-02
      • 2015-11-13
      • 2015-10-16
      • 1970-01-01
      • 2013-09-14
      相关资源
      最近更新 更多