使用cookie将活动类添加到当前元素

时间:2018-10-24 06:39:04

标签: javascript jquery twitter-bootstrap navigation

我试图在重新加载页面时保持活动类,为此我创建了Fiddle,在Stackoverflow上的某个地方找到了JS代码,但我没有设法使其正常工作。我想向父元素和子元素添加活动类。

<ul id="nav" class="navHolder">
<li><a href="#"><i class="fa fa-home"></i> Home</a></li>

<li class="subNav ">
    <a href=""><i class="fa fa-shopping-cart"></i> Shop</a>
 <ul>
    <li><a href="#">Men
        </a></li>
    <li><a href="#">Women</a></li>
    <li><a href="#">Kids</a></li>
 </ul>
  </li>
</ul>

这是来自Stackoverflow的JS:

    $( "li" ).click(function(e) {
    $("li").removeClass("active");
    $(e.target).parent("li").addClass("active");
    $(e.target).parent("li").parents("li").addClass("active");

    var x = 0;
    $("li").removeClass("setCookie");
    $(this).addClass("setCookie");
        $('#nav').children('li').each(function () {
        if ($(this).hasClass("setCookie")) {
            createCookie("setCookie", x, 2); 
        } 
        x = x+1;
    });    
   });

  $(document).ready(function() {
    $("li").removeClass("active");
    var x = 0;
    var setCookie = readCookie("setCookie");
    $('#nav').children('li').each(function () {
        if (setCookie==x) $(this).addClass("active");
        x = x+1;
    }); 
  });

  function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + 
     encodeURIComponent(value) + expires + "; path=/";
  }

  function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0)
            return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
  }

任何想法如何解决这个问题? Fiddle

0 个答案:

没有答案