在jquery中突出显示当前页面 [英] Highlight current page in jquery

查看:207
本文介绍了在jquery中突出显示当前页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the 12 html pages. and all this pages are loads when the left navigation bar link clicked. in this, i need to add a class to the current link, which is clicked and loaded the page. i tried with this:

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

    })
})

它有效,但在页面加载时,该类被删除,我不知道它为什么会发生..

it works, but on page load, the class is removed, i don't know why it's happening..

任何帮助?

推荐答案

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

Jimmy is right. When you reload a page, the browser also refreshes the Javascript code, which means all the variables and settings you made will also be reset. This is why the class appears to be removed when you click on the link.

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

The solution here would be to modify your code to loop through all the links and compare each one to the current page's URL. When you find a match, then call the addClass function for that link to change its colour. So, something like this should work:

$(function(){

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

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

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

Note that we are calling this looping function on page load, rather than calling it when user clicks on a link... because clicking on a link will cause the page to reload which will reset all the JQuery variables.

希望这会有所帮助。

这篇关于在jquery中突出显示当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆