添加/删除类,并使用Cookie记住选择 [英] Add/Remove classes and using Cookie to remember selection

查看:120
本文介绍了添加/删除类,并使用Cookie记住选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段简单的JQuery,可以切换锚标记/链接上的类. 我不知道单击其他链接时如何使类切换或添加/删除?示例:该类只能应用于单击的链接,并且一次不能超过一个.那就是我被困住的地方.好吧,我不知道该怎么做.

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.

第二,如何使用JQuery Cookie保持当前链接处于活动状态.我已经下载了Cookie扩展程序.

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

这是我所做的:

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');
}); 
});

谢谢!

推荐答案

以下是使用事件传播的解决方案:

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();

});​

这是一个演示(没有cookie功能,因为JSFiddle缺乏支持).

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

这篇关于添加/删除类,并使用Cookie记住选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆