使用jQuery添加基于URL的类 [英] Using jQuery To Add Class Based On URL

查看:81
本文介绍了使用jQuery添加基于URL的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery,并试图基于URL向菜单项添加一个类.我尝试了这个(在其他主题中找到),但是无法使其正常工作.它将类添加到当前页面URL之后的每个菜单项.

I'm using jQuery and I'm trying to add a class to a menu item based on URL. I tried this(found in other topics), but cannot get it to work properly. It adds the class to every menu item after the current page url.

这是我的代码:

<script type='text/javascript'>
  $(document).ready(function(){
    $(function() {
        switch (window.location.pathname) {
            case '/p/about.html':
                    $('.nav-about').addClass('current')
            case '/search/blog':
                    $('.nav-blog').addClass('current')
            case '/p/design.html':
                    $('.nav-design').addClass('current')
            case '/p/photography.html':
                $('.nav-photography').addClass('current')
            case '/p/hosting.html':
                $('.nav-hosting').addClass('current')
        }
      });
  });
</script>

有任何纠正建议吗?

谢谢.

对于那些询问,我正在使用Blogger.我没有使用默认的链接列表",而是创建了自己的响应菜单.这里只有一个模板,所以并不是我可以向每个HTML页面添加一个类.这将必须使用jQuery完成,因为Blogger不会向特定页面添加特定的类.因此,我需要获取URL才能将适当的类应用于适当的菜单项.

for those asking, I am using Blogger. Instead of using the default "Link-List", I created my own responsive menu. There is only one template here, so it's not like I can add a class to each HTML page. It's gonna have to be done with jQuery, because Blogger doesn't add specific classes to specific pages. So I need to grab the URL to apply the appropriate class to the appropriate menu item.

推荐答案

在每种情况下都需要一个break,否则它将继续进行下一个.

You need a break after each case or else it will just go on to the next one.

switch (window.location.pathname) {
    case '/p/about.html':
       $('.nav-about').addClass('current');
       break;
    case '/search/blog':
       $('.nav-blog').addClass('current');
       break;
    case '/p/design.html':
       $('.nav-design').addClass('current');
       break;
    case '/p/photography.html':
       $('.nav-photography').addClass('current');
       break;
    case '/p/hosting.html':
       $('.nav-hosting').addClass('current');
       break;
}


要点,这是重复的:


Side point, this is repetitive:

  $(document).ready(function(){
    $(function() {

这两个都是同一件事,请使用其中之一.

Both of those mean the same thing, use one of them.

这篇关于使用jQuery添加基于URL的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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