简体   繁体   English

如何使用jQuery和JavaScript将类添加到元素?

[英]How to add a class to an element using jQuery and javascript?

I have the HTML code as given below to add the navigation to my site. 我具有如下所示的HTML代码,可将导航添加到我的网站。 (Note that the list is nested) (请注意列表是嵌套的)

<div id="navigation">
       <ul>
        <li><a href="default.html">Home</a></li>
        <li><a href="about.html">About us</a></li>
        <li><a href="help.html">Help</a></li>
        <li><a href="#">DropDown</a>
          <ul>
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
          </ul>
        </li>
        <li class="last"><a href="#">A Last Link Text</a></li>
      </ul>
</div>

I want to show the currently active page link in new color. 我想以新颜色显示当前活动的页面链接。 So the corresponding list item should have the class active and I use the CSS to change the color. 因此,相应的列表项应具有活动的类,并且我使用CSS来更改颜色。 For example, if the default.html is the currently opened page, the code should be <li class=“active”><a href="default.html">Home</a></li> . 例如,如果default.html是当前打开的页面,则代码应为<li class=“active”><a href="default.html">Home</a></li>

How to do that in jQuery and JavaScript (I need both for two different websites). 如何在jQuery和JavaScript中做到这一点(我需要两个不同的网站)。 Can anyone help me? 谁能帮我?

Thanks for your help. 谢谢你的帮助。

Get your URL / Parse it: 获取您的网址/解析它:

var pathname = window.location.pathname;

Then add the class: 然后添加类:

Jquery: jQuery:

$(element).addClass('classname');

JS: How do I add a class to a given element? JS: 如何将类添加到给定的元素?

Try this 尝试这个

$(document).ready(function () {
    var url = location.href;
    $('#navigation li a').each(function () {
        var thisHref = this.getAttribute('href');
        if (thisHref !== '#' && url.indexOf(thisHref) !== -1) {
            $(this.parentNode).addClass('active');
            return;
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM