Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Add/Remove classes and using Cookie to remember selection

I have this simply piece of JQuery that toggle a class on anchor tags/links. What I don't know is how do I make the class toggle or add/remove when the other links are clicked? Example: The class can only apply to the link that is click and cannot be on more than one at a time. That's where I am stuck. Well, I don't know how to do it.

Secondly how do I use the JQuery Cookie to keep the currently link active. I have downloaded the cookie extension.

Here is what I have done:

HTML:

<ul class="navbar">
 <li><a  href="#/">Link1</a></li>
 <li><a href="#/">Link2</a></li>
 <li><a  href="#/">Link3</a></li>
</ul>

CSS:

.activeLink{
    color: #930;
}

JQuery:

$(document).ready(function() {
$('.navbar li a').click(function(){
    $(this).toggleClass('activeLink');
}); 
});

Thank you!!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Below is a solution that uses event propagation:

$(function() {

    var $activeLink,
        activeLinkHref = $.cookie('activeLinkHref'),
        activeClass = 'activeLink';

    $('.navbar').on('click', 'a', function() {
        $activeLink && $activeLink.removeClass(activeClass);
        $activeLink = $(this).addClass(activeClass);
        $.cookie('activeLinkHref', $activeLink.attr('href'));
    });

    // If a cookie is found, activate the related link.
    if (activeLinkHref) 
    $('.navbar a[href="' + activeLinkHref + '"]').click();

});?

Here's a demo (without the cookie functionality as JSFiddle lacks support).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...