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
380 views
in Technique[技术] by (71.8m points)

javascript - How to change active class while click to another link in bootstrap use jquery?

I have a html as sidebar, and use Bootstrap.

<ul class="nav nav-list">
    <li class="active"><a href="/">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
    <li><a href="/link3">Link 3</a></li>
</ul>

I want to do some thing:

When I click a link such as Link 3, the page content will change to Link 3's content, and the Link 3 will have class active, and remove the active clss in Link 1.

I think this can be implemented in jQuery, and I have searched many question in SO, such as:

I use this script:

$(document).ready(function () {
    $('.nav li').click(function(e) {

        $('.nav li').removeClass('active');

        var $this = $(this);
        if (!$this.hasClass('active')) {
            $this.addClass('active');
        }
        //e.preventDefault();
    });
});

But most of them use preventDefault, this will prevent the continued action. So it can't change to Link 3's page content.

If I remove the preventDefault statement, when the page load Link 3's content, the active class will back to Link 1.

So Is there any way to solve this problem?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are binding you click on the wrong element, you should bind it to the a.

You are prevent default event to occur on the li, but li have no default behavior, a does.

Try this:

$(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

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

...