I got this Jq to add active class to <li> tag:

$("#main-nav li").each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("active");
            //alert(this.href.trim());
    });

html:

<div class="navbar-collapse collapse">
      <ul class="nav navbar-nav" id="main-nav">
        <li><a href="index.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="contact.php">Contact</a></li>
</div>

But somehow it doesn't works, can anyone please look after what's goes wrong?

有帮助吗?

解决方案

You need to loop through the anchors, not the list items. The href is a property of the anchor. Do that loop and you can then apply .addClass() to the closest list item. Also, if you are using jQuery, you may as well use the reliable jQuery trim():

$("#main-nav li a").each(function(index) {
    if($.trim(this.href) == window.location) {
        $(this).closest('li').addClass("active");
        //alert(this.href.trim());
    }
});

其他提示

You are not going to get href using this.href.trim().you need to use:

$(this).find('a').attr('href').trim()

My version:

$("#main-nav li a").each(function(index) {
    if(this.href.trim() == window.location)
        $(this).parent().addClass("active");
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top