Toggle URL parameter with button

2019-02-20 04:30发布

问题:

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 remembered when the user visits the site the next time. I wouldn't like to use jQuery plugins.

Also I would like to add a parameter to the url on button click like ?title=0 where the number would represent the current state of the element, and the state would be also controllable this way.

Here is an example:

$('#hide').click(function(){
  $('h1').toggleClass('hidden');
  $(this).text() == 'Hide title' ?
    $(this).text('Show title') :
    $(this).text('Hide title');
});
.hidden {
    visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<button id="hide">Hide title</button>
<h1>Title</h1>

回答1:

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