Keep the same colour after page refresh

2019-05-15 04:57发布

问题:

When I click the div, the color of the span changes to red, as i expected, but when I refresh my page the color isn't red, it returns back to original color, in my case green. How can I preserve the same color (red) after refreshing the page? I event tried with .apend() but the situation is the same.

This is my HTML:

  <span>Green</span>
  <div id="changeColor"> </div>

jQuery:

$('#changeColor').click(function(){

$('span').css({"background-color":"red"});

});

Thank you all :D

回答1:

Take a look at this jQuery cookie plugin. You can use it (or a smilar plugin) to create / read and store information in cookies. Then when the page loads you can use this cookie to set the color of the div as it is stored in the cookie.

Here is an example JSFiddle.

I hope this helps!



回答2:

You'll need to store the value in a cookie, test the value of the cookie when the page loads and set the color of the div accordingly.



回答3:

You would need to save your information in a Cookie. Other than that, or using some kind of database, there is no way to retain information after a page refresh.