在jquery中突出显示当前页面

3gw*_*ain 3 javascript regex jquery

我有12个html页面.单击左侧导航栏链接时会加载所有这些页面.在这里,我需要在当前链接中添加一个类,单击并加载页面.我试过这个:

$(function(){
    $('#container li a').click(function(){
        $('#container li a').removeClass('current');
        var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
        var currentPage = $(this).attr('href');

        if(currentPage==pathname){
            $(this).addClass('current');
        }
        else{
            alert('wrong');
        }

       // alert(pathname+' currentPage: '+currentPage);

    })
})
Run Code Online (Sandbox Code Playgroud)

它工作,但在页面加载,类被删除,我不知道为什么它发生..

任何帮助?

Bug*_*net 6

吉米是对的.当您重新加载页面时,浏览器还会刷新Javascript代码,这意味着您所做的所有变量和设置也将被重置.这就是您单击链接时类似乎被删除的原因.

这里的解决方案是修改您的代码以遍历所有链接,并将每个链接与当前页面的URL进行比较.找到匹配项后,请调用该链接的addClass函数以更改其颜色.所以,这样的事情应该有效:

$(function(){

    var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);

    $('#container ul li a').each(function() {
    if ($(this).attr('href') == pathname)
    {
        $(this).addClass('current');
    }
    });
});
Run Code Online (Sandbox Code Playgroud)

请注意,我们在页面加载时调用此循环函数,而不是在用户单击链接时调用它...因为单击链接将导致页面重新加载,这将重置所有JQuery变量.

希望这可以帮助.


Fen*_*ton 6

使用jQuery,我总是认为最好使用jQuery选择器来过滤你想要影响的元素,而不是自己循环遍历它们.这是我的解决方案:

$(document).ready( function () {
    var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
    $("#container li a").removeClass("current");
    $("#container li a[href='" + pathname  + "']").addClass("current");
});
Run Code Online (Sandbox Code Playgroud)