根据网页网址更新类属性 [英] Update class attribute based on page URL

查看:143
本文介绍了根据网页网址更新类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,其中活动菜单项具有与其他菜单项不同的样式:

I have this code, where an active menu item has different styling to other menu items:

<div class="menu">
<li class="active"><a href="item1.php">Item 1</a></li>
<li><a href="item2.php">Item 2</a></li>
<li><a href="item3.php">Item 3</a></li>
</div>

而不是手动代码class =活动不同的每个页面,我想试试这个

Rather than manually code class="active" differently for each page, I'd like to try this with a script that automatically inserts the class to the li tag, based on whether the anchor is the current URL.

任何人都知道我该如何开始这个?

Anybody know how I might start this?

推荐答案

尝试以下代码:

$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu

  var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)

    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active"); // remove all active class    
        $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
   }
});

这篇关于根据网页网址更新类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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