Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

jquery - Twitter Bootstrap add active class to li

Using twitter bootstrap, and I need to initiate active class to the li portion of the main nav. Automagically. We use php not ruby.

Sample nav :

<ul class="nav">
    <li><a href="/">Home</a></li>
    <li><a href="/forums">Forums</a></li>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/faqs.php">FAQ's</a></li>
    <li><a href="/item.php">Item</a></li>
    <li><a href="/create.php">Create</a></li>
</ul>

Bootstrap code is as follows:

<li class="active"><a href="/">Home</a></li>

So just need to figure out how to append the class active to the current page. Have looked thru nearly every answer on Stack, with no real joy.

I had played with this:

/*menu handler*/
$(function(){
    var url = window.location.pathname;  
    var activePage = url.substring(url.lastIndexOf('/')+1);
    $('.nav li a').each(function(){  
        var currentPage = this.href.substring(this.href.lastIndexOf('/')+1);

        if (activePage == currentPage) {
            $(this).parent().addClass('active'); 
        } 
    });
})

But no joy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Bootstrap 3:

var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');

// Will also work for relative and absolute hrefs
$('ul.nav a').filter(function() {
    return this.href == url;
}).parent().addClass('active');

Update

For Bootstrap 4:

var url = window.location;
// Will only work if string in href matches with location
$('ul.navbar-nav a[href="'+ url +'"]').parent().addClass('active');

// Will also work for relative and absolute hrefs
$('ul.navbar-nav a').filter(function() {
    return this.href == url;
}).parent().addClass('active');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...