使用jQuery激活多个lavel下拉菜单

时间:2016-01-28 06:54:57

标签: javascript jquery cookies

点击菜单示例" C"然后我想设置课程活跃。重新加载页面后它也应该是活动的。

<ul class="nav metismenu" id="side-menu">                 
<li>
    <a href="#">Dashboards</a>
    <ul class="nav nav-second-level collapse">
        <li><a href="#A">A</a></li>
        <li><a href="#B">B</a></li>
        <li><a href="#C">C</a></li>
        <li><a href="#D">D</a></li>
        <li><a href="#E">E</a></li>
    </ul>
</li>
<li>
    <a href="F">F</a>
</li>   
</ul>    

要设置一个活动的类,代码为:

<ul class="nav metismenu" id="side-menu">                 
<li class="active">
    <a href="#">Dashboards</a>
    <ul class="nav nav-second-level collapse">
        <li><a href="#A">A</a></li>
        <li><a href="#B">B</a></li>
        <li class="active"><a href="#C">C</a></li>
        <li><a href="#D">D</a></li>
        <li><a href="#E">E</a></li>
    </ul>
</li>
<li>
    <a href="F">F</a>
</li>   
</ul>    

1 个答案:

答案 0 :(得分:3)

首先,我邀请您详细了解cookies

所以,对于这种情况,这里是工作小提琴=&gt; jsFiddle 我在小提琴中使用了JQuery(别忘了在你的资源中使用Jquery)

ps:出于安全问题,Snippet无法在这里工作!!

JS:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.your_item_layout, parent, false);
    }
    ....
    if (getItem(position).get("attendance").equals("absent")) {   
        convertView.setBackgroundColor(getContext().getColor(R.color.bg_color_absent));
    } else {      
        convertView.setBackgroundColor(getContext().getColor(R.color.bg_color_normal));
    }

    return convertView;
}

CSS:

$( document ).ready(function(){
  if(typeof(getCookie("activeLi")) != "undefined" && getCookie("activeLi").length>0){
    $('#side-menu ul a[ href=' + getCookie("activeLi") + ']').parent().addClass("active");
  }
  $("#side-menu ul a").click(function(a){
        if(typeof(getCookie("activeLi")) != "undefined");
        alert(getCookie("activeLi"));
        removeActive();
        $(this).parent().addClass("active");
      setActiveCookie(this.getAttribute("href"));
  });
});

function removeActive(){
    $("#side-menu ul li").each(function(li){
    $(this).removeClass("active");
  })
}

function setActiveCookie(active){
      //document.cookie="activeLi="+active;
    var d = new Date();
    d.setTime(d.getTime() + (30*24*60*60*1000)); // expire in 30 days
    var expires = "expires="+d.toUTCString();
    document.cookie="activeLi="+active+"; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

HTML:

.active a {
  color: green;
}
a {
  text-decoration: none;
}