jQuery如何将类添加到<li>或<a> and keep it on the next page load or refresh?</a> </li>

时间:2014-02-24 19:31:31

标签: javascript jquery html html5 class

我有<li>个元素,包含<a>个元素。当用户点击<a>时,它会将“有效”类设置为<a>并加载新链接。但是当加载新链接时,类“活动”消失。如何在新页面出现时仍然在同一个<a>上进行“有效”课程?

由于

3 个答案:

答案 0 :(得分:2)

基本上,您需要在页面更改之间保持状态。您可以通过以下两种方式之一来实现:

  1. 会话参数:使用Cookie或本地存储(HTML5)
  2. 请求参数:添加URL参数并通过jquery读取(例如:http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html

答案 1 :(得分:0)

最快最简单的方法是将其保存在cookie中。以下是如何创建/读取Cookie的示例代码: LINK

在您的情况下,您需要为每个<a><li>添加ID或一些唯一属性,以便在页面重新加载时,脚本知道应激活哪个<a>,例如:

<强> HTML

<li><a href="abc.html" data-unique-attr="123">link 1</a></li>
<li><a href="def.html" data-unique-attr="456">link 2</a></li>
<li><a href="ghi.html" data-unique-attr="789">link 3</a></li>

<强>的jQuery

// on page load: read the cookie and activate the link
$(function() {
    var activeAnchor = readCookie('activeAnchor');
    if (activeAnchor) {
        $('li a[data-unique-attr="' + activeAnchor + '"]').addClass('active');
    }
});

// on click: set the cookie
$('li a').click(function() {
    $(this).addClass('active');
    createCookie('activeAnchor', $(this).data('uniqueAttr'));
});

答案 2 :(得分:0)

如果相关链接与网页的网址相匹配,您可以将代码基于该代码而不是Cookie或其他内容。

$(function() { //The document is ready...
    $('li a[href="' + window.location.href + '"]').addClass('active');
});

请注意,在此表单中,仅当链接是绝对链接时才起作用,即从http://开始。如果链接是相对的,您可能需要稍微调整一下。