简体   繁体   中英

HTML5 & jQuery LocalStorage

This is my first go at localStorage and its not going. I have the jQuery code below to increase the page font size if an element is selected. Problem is when you go to a new page, it reverts back. I've tried some different variations but I am stuck. Any help is appreciated.

$textSize1.click(function() {
  $( "body" ).css("font-size", "10px");
  localStorage.setItem("$textSize1", $textSize1);
});
$textSize2.click(function() {
  $( "body" ).css("font-size", "20px");
  localStorage.setItem("$textSize2", $textSize2);
});
$textSize3.click(function() {
  $( "body" ).css("font-size", "30px");
  localStorage.setItem("$textSize3", $textSize3);
});

localStorage.getItem("$textSize1");
$textSize1.click(function() {
  $( "body" ).css("font-size", "10px");
  localStorage.setItem("$textSize1", $textSize1);
});
$textSize2.click(function() {
  $( "body" ).css("font-size", "20px");
  localStorage.setItem("$textSize2", $textSize2);
});
$textSize3.click(function() {
  $( "body" ).css("font-size", "30px");
  localStorage.setItem("$textSize3", $textSize3);
});

localStorage.getItem("$textSize1");

What is happening is that you are storing the value and fixing the style in the current page but you are not doing the same operation when the page load again.

This is normally done in the onReady written in jQuery like this : $(document).ready(function() {...});

Just reading the value won't do much. You need to use it!

I think I've captured what you were trying to do and reimplemented your code:

var defaultFontSize = "10px";

$(document).ready(function(){
    var fontSize = localStorage.getItem("fontSize") || defaultFontSize;
    $( "body" ).css("font-size", fontSize);
})

$fontSize1.click(function() {
  $("body").css("font-size", "10px");
  localStorage.setItem("fontSize", "10px");
});
$fontSize2.click(function() {
  $("body").css("font-size", "20px");
  localStorage.setItem("fontSize", "20px");
});
$fontSize3.click(function() {
  $("body").css("font-size", "30px");
  localStorage.setItem("fontSize", "30px");
});

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