使用jQuery存储单击的链接状态?

$('#nav a').click(function () { $('#nav a').removeClass('current'); $(this).addClass('current'); return false; }); 

我的HTML是:

  

如果它有帮助,我的URL是: Karls示例站点

使用上面的jQuery代码 – 当用户刷新页面时,如何存储最后点击的链接? 我是jQuery的初学者,虽然我已经看过那里的答案,但大多数都是用滑块或手风琴做的,所以在我学习遏制的这个阶段让我理解得太复杂了! 🙂

请有人帮忙,如果需要的话,也可以展示如何实现代码或插​​件(我在网上看到了一个cookie插件)

你的链接有ID吗? 如果是这样,只需在点击时将ID存储在cookie中。 所以,像这样:

 $('#nav a').click(function () { $.cookie('lastclicked',this.id); $('#nav a').removeClass('current'); $(this).addClass('current'); return false; }); 

使用jQuery cookie插件可以减少直接设置cookie的烦恼因素。 在页面加载时,查找cookie(请参阅文档),读取其值(如果存在),现在您知道最后一次单击链接的ID。

首先,您需要一种方法来唯一地标识链接 – 无论是id还是href属性都可以。 接下来,获取将为您处理cookie的代码。 我将使用quirksmode.org中的那个 。

您可以存储上次使用的锚的唯一标识符,如下所示:

 $('#nav a').click(function(){ $(this).addClass('current').siblings().removeClass('current'); // Create a cookie that will last 30 days with // the name "link" containing this anchor's id attribute createCookie('link', this.id, 30); return false; }); 

加载下一页时,请按以下方式读取cookie:

 var lastLink = readCookie('link'); if(lastLink){ $('#' + lastLink).addClass('lastVisited'); } 

为何使用cookies? 您的链接具有哈希属性,因此我只需在动画完成后手动设置位置栏的哈希值。

您没有包含执行滚动动画的代码,但是存储了在变量中单击的的哈希值,然后在动画的回调中设置了location.hash

就像是:

 $('a').click(function() { // get the hash from the link var hash = this.hash; // Do the animation. (This is just example code.) // In the callback to the animation, manually set the location bar's hash $(document.body).animate({scrollLeft: 500}, 600, function() { location.hash = hash; }); return false; }); 

然后,如果用户刷新页面,则哈希将在那里。

然后,您可以通过使用location.hash检索散列,在页面加载时将用户直接带到正确的部分。 这将使部分可collections。

我使用jQuery Address插件而不是cookie,这样它可以在浏览器窗口/标签上工作,并且它还提供深层链接。

 $('#nav a').click(function () { $.address.parameter('lastclicked', this.id); $('#nav a').removeClass('current'); $(this).addClass('current'); return false; });