简体   繁体   中英

Set cookie to menu jquery

I have a code:

I have two buttons and two list. This is my code code:

 $(document).on('mouseenter', '.select-user-type-js', function() { $('.select-user-type-js.active').add($(this)).toggleClass('active'); if ($(this).hasClass('select-user-type_customer')) { $('#buyer').show(); $('#seller').hide(); } else { $('#buyer').hide(); $('#seller').show(); } }); $(document).on("click", ".select-user-type-js", function() { if ($(this).hasClass('select-user-type_customer')) { $.cookie("tab", 'select-user-type_customer'); } else { $.cookie("tab", 'select-user-type_performer'); } }); if ($.cookie("select-user-type_customer")) { $('#buyer')).show(); $('#seller').hide(); $('.select-user-type_performer').not($(this)).removeClass('active'); } else { $('#seller')).show(); $('#buyer').hide(); $('.select-user-type_customer').not($(this)).removeClass('active'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="select-user-type-js select-user-type_customer active">Customer</a> <a href="" id="seller" class="select-user-type-js select-user-type_performer">Seller</a> <ul id="buyer"> <li><a href="#">Menu for buyer #1</a></li> <li><a href="#">Menu for buyer #2</a></li> <li><a href="#">Menu for buyer #3</a></li> </ul> <ul id="seller" style="display: none;"> <li><a href="#">Menu for seller #1</a></li> <li><a href="#">Menu for seller #2</a></li> <li><a href="#">Menu for seller #3</a></li> </ul> 

How I can write to cookie menu? When user reload to page, to save the menu that he chose, when clicking to specific button..? My Code is not working for cookie

Here is a working demo of your example with Cookie

$(document).on('mouseenter', '.select-user-type-js', function() {
  $('.select-user-type-js.active').add($(this)).toggleClass('active');
  if ($(this).hasClass('select-user-type_customer')) {
    $('#buyer').show();
    $('#seller').hide();
  } else {
    $('#buyer').hide();
    $('#seller').show();
  }
});

$(document).on("click", ".select-user-type-js", function(e) {
  e.preventDefault()
  if ($(this).hasClass('select-user-type_customer')) {
    Cookies.set("tab", 'select-user-type_customer');
  } else {
    Cookies.set("tab", 'select-user-type_performer');
  }
});

if (Cookies.get("tab") == 'select-user-type_customer') {
  $('#buyer').show();
  $('#seller').hide();
  $('.select-user-type_customer').addClass('active');
} else {
  $('#seller').show();
  $('#buyer').hide();
  $('.select-user-type_performer').AddClass('active');
}

when you need to check the cookie value you have to do Cookies.get("tab") == 'select-user-type_customer' and not Cookies.get("select-user-type_customer")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM