简体   繁体   English

HTML5和jQuery LocalStorage

[英]HTML5 & jQuery LocalStorage

This is my first go at localStorage and its not going. 这是我第一次去localStorage而不去。 I have the jQuery code below to increase the page font size if an element is selected. 如果选择了一个元素,我有下面的jQuery代码来增加页面字体大小。 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() {...}); 这通常在用jQuery编写的onReady完成,如下所示: $(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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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