添加/删除类,并使用Cookie记住选择 [英] Add/Remove classes and using Cookie to remember selection
问题描述
我有一段简单的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屋!