Toggle URL parameter with button

前端 未结 1 1303
予麋鹿
予麋鹿 2021-01-16 15:10

I have a button on my website that toggles the visibility of an element with jQuery.

How can I store the state of this element in a cookie or local storage? So it is

相关标签:
1条回答
  • 2021-01-16 15:55

    Note, untested at stacksnippets , which does not allow use of localStorage

    Try utilizing $.holdReady() , localStorage

    $.holdReady(true);   
    // hide title
    if (location.search === "?title=0") {
      if (!localStorage.getItem("title"))   {
        localStorage.setItem("title","0");  
      } else {
        localStorage.setItem("title","0");  
      }
      $("#hide").text("Show title");
      $("h1").addClass("hidden");
      // location.search = "?title=0";
    }
    // show title
    if (location.search === "?title=1") {
      if (!localStorage.getItem("title"))   {
        localStorage.setItem("title","1");  
      } else {
        localStorage.setItem("title","1");  
      }
      $("#hide").text("Hide title");
      $("h1").removeClass("hidden");
      // location.search = "?title=1"
    }    
    $.holdReady(false);
    $(document).ready(function() {
        $('#hide').click(function() {
          $('h1').toggleClass('hidden');
          $(this).text() == 'Hide title' ?
            $(this).text('Show title') && localStorage.setItem("title", "0") :
            $(this).text('Hide title') && localStorage.setItem("title", "1");
        });
        location.search = "?title=" + localStorage.getItem("title");
    });
    

    See also Global Variable usage on page reload

    0 讨论(0)
提交回复
热议问题