문제

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