【问题标题】:Add Active Class to Selected Page (With and Without Trailing Slash)将活动类添加到选定页面(带和不带斜杠)
【发布时间】:2015-07-08 20:11:28
【问题描述】:

我有一个选择器,它将“活动”类添加到所选页面。 然而,它只能与斜杠一起使用,例如如果是:

Site.com/TEST/ 它工作正常。

但是,如果它的 Site.com/TEST 没有。

这在使用“返回”按钮时会导致问题,因为它会将我带回页面但没有尾随“/”

这是我的代码:

$(document).ready(function () {
    $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
});

有人可以修改它以将类添加到两种变体中吗? 另外,如果可能的话,如果我选择父级的子页面,是否可以对其进行修改,以便将活动类添加到父级?

例如Site.com/Test/Edit 我想将测试设置为活动状态。

谢谢

【问题讨论】:

    标签: java jquery html css asp.net-mvc-4


    【解决方案1】:

    str.replace(/\/+$/,'') + '/' 将始终确保字符串以 / 结尾,因此您的代码将如下所示:

    $(document).ready(function () {
        str = this.location.pathname.replace(/\/+$/,'') + '/';
        $('a[href="' + str + '"]').parent().addClass('active');
    });
    

    如果您不知道是否所有链接都以斜线结尾,那么您可以检查所有内容:

    $(document).ready(function () {
        str1 = this.location.pathname.replace(/\/+$/,'') + '/';
        str2 = this.location.pathname.replace(/\/+$/,'');
        $('a[href="' + str1 + '"], a[href="' + str2 + '"]').parent().addClass('active');
    });
    

    编辑

    让我们尝试选择所有父链接:

    var tmp = this.location.pathname.replace(/.*?:\/\//g, "").replace(/\/+$/,'');
    arr = tmp.split('/');
    while(arr.length > 1) {
      tmp = 'http://' + arr.join('/');
      $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addClass('active');
      arr = arr.slice(0,-1);
    }
    

    基本上我从开头删除http:// 并将字符串拆分为每个/ 上的数组元素。然后我将一个一个地删除结束元素,再次粘合并相应地构造选择器。

    这是在行动,它是如何生成链接的:

    $('#test').click(function(){
      
      // I replaced the string with the input value for testing
      var tmp = $('input').val().replace(/.*?:\/\//g, "").replace(/\/+$/,'');
      arr = tmp.split('/');
      
      // Clearing the output here
      $('div').html('');
      while(arr.length > 1) {
        tmp = 'http://' + arr.join('/');
        
        // Appending the current result
        $('div').append('<p>' + tmp + '/</p>');
        $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addClass('active');
        arr = arr.slice(0,-1);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input value="http://google.com/sub1/sub2">
    <button id="test">test</button>
    <div></div>

    【讨论】:

    • 这太棒了,非常感谢!厚脸皮我知道,但你知道我如何修改它以在选择子页面时使父“活动”,例如Site.com/TEST/Edit 仍会将 TEST 链接设为 Active 属性
    • 嘿,谢谢,不幸的是,现在这似乎根本不起作用!
    • 用测试仪再次更新。
    • 嘿,很遗憾没有,但我想我现在应该没事了。非常感谢您的努力,我很感激。
    • Skatch - 我不知道这是否有用,但该项目正在使用 MVC4。我仍然无法让子页面为父级提供活动课程。例如。 site.com/questions 工作正常并应用了活动。如果我访问 site.com/questions/create,我希望 Questions 仍然是活跃的课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 2011-05-25
    相关资源
    最近更新 更多