JavaScript session 存储 : unexpected value change

标签 javascript html cookies web session-storage

我为我的网站制作了一个小“字体大小小部件”。现在,今天我正在考虑实现 session 存储,以便用户不必一直单击按钮。

标准字体大小是20。现在,我不知道为什么,但有时,只有当我点击button2(以获得更大的尺寸)时,该值才变成字面上的20 + 2 => 202。我不知道如何或为何。

有人知道如何提高性能并解决此代码吗?或者,如果您认为 cookie 是一个更好的主意,我将如何为这段代码实现 cookie?

var currentSize;
function confSize(){
  if (sessionStorage.getItem('sessionSize') == ""){
      $("#body").css("font-size", "20px");
  }
  else {
      currentSize = sessionStorage.getItem('sessionSize');
      $("#body").css("font-size", currentSize + "px");
      console.log(sessionStorage.getItem('sessionSize'))
  }


    $("#button2").click(function(){
        if (currentSize == 20){
            currentSize = 22;
        }
        else {
            currentSize = currentSize + 2;
        }

        sessionStorage.setItem('sessionSize', currentSize);
        $("#body").css("font-size", currentSize + "px");
    });

    $("#button").click(function(){
        currentSize -= 2;
        sessionStorage.setItem('sessionSize', currentSize);
        $("#body").css("font-size", currentSize + "px");
    });

}

最佳答案

您需要确保正确使用适当的字符串和整数值。如果您执行如下操作:

currentSize = currentSize + 2

根据 currentSize 当前是字符串还是整数,您将获得不同的值。如果它是一个字符串,您会遇到您注意到的串联问题。

现在,您实际上将其与以下问题混合在一起:当您将整数 currentSize 值插入 sessionStorage 时,会自动进行整数到字符串的转换以进行存储(从技术上讲)无论您尝试存储什么内容,都会调用 .toString() 方法来确定要存储的字符串值)。您从 sessionStorage 检索的内容始终是一个字符串值,因此您需要在尝试对其进行整数数学运算之前将其转换回整数。

我建议修改您的代码以明确字符串/整数。可能看起来像这样:

var currentSize;
function confSize(){
   var defaultSize = 20;
   var sessionStorageStr = sessionStorage.getItem('sessionSize');
   if (sessionStorageStr == ""){
      currentSize = defaultSize;
   }
   else {
      currentSize = parseInt(sessionStorageStr);
      console.log(currentSize);
   }

   // no need to repeat this code in both sides of the conditional above
   $("#body").css("font-size", currentSize + "px");


   $("#button2").click(function(){
        // I removed your conditional here, as it really did nothing        
        currentSize += 2;
        sessionStorage.setItem('sessionSize', currentSize);
        $("#body").css("font-size", currentSize + "px");
    });

    $("#button").click(function(){
        currentSize -= 2;
        sessionStorage.setItem('sessionSize', currentSize);
        $("#body").css("font-size", currentSize + "px");
    });
}

关于JavaScript session 存储 : unexpected value change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253680/

相关文章:

javascript - 开始使用 Ember.js

javascript - 如何为 html5 canvas 实现喷漆工具?

php - 使用 Session 或 Cookie 登录

php - Codeigniter 无法删除 cookie

node.js - Express 没有设置 cookie

javascript - 在html表格上正确添加水平滚动条

javascript - 幻灯片上的图像向下跳跃

html - 在其他两个 div 之间垂直放置 div 文本

javascript - 为每个信息生成按钮

html - 如何在没有计算的情况下实现这种等距布局?