简体   繁体   English

如何在单击按钮时增加本地存储中的值?

[英]How to increment value in localstorage on button click?

In one screen of my web app, a user has entered a numerical value which is stored in the localstorage.在我的 Web 应用程序的一个屏幕中,用户输入了一个存储在 localstorage 中的数值。 In the next screen the user can click a button where the localstorage value will be incremented by a value once;在下一个屏幕中,用户可以单击一个按钮,其中 localstorage 值将增加一次; lets say add 5. So if the localstorage of the variable X is 5 on button click it will be updated to 10.假设加 5。所以如果变量 X 的 localstorage 在按钮单击时为 5,它将被更新为 10。

How do I go about this?我该怎么做? I have the value stored but I don't know how to manipulate the value on button click.我存储了该值,但我不知道如何在单击按钮时操作该值。

codepen with my current localstorage implemented using a range slider as input.使用范围滑块作为输入实现我当前本地存储的 codepen。

https://codepen.io/anon/pen/WMqrqe https://codepen.io/anon/pen/WMqrqe

var updateValuesMinutes = function(){
$to.prop("value", to);
localStorage.setItem( 'StoreMinutes', to); 
let localMinutes = localStorage.getItem("StoreMinutes"); 
console.log(localMinutes); 
};

You're only missing 1 line of code to get this working:您只缺少 1 行代码即可使其正常工作:

var updateValuesMinutes = function(valueToIncrementBy){
  $to.prop("value", to);
  localStorage.setItem( 'StoreMinutes', to); 
  let localMinutes = localStorage.getItem("StoreMinutes"); 
  console.log(localMinutes); 
  // This is what you're missing.

  localStorage.setItem('StoreMinutes', !isNaN(parseInt(localMinutes)) ? parseInt(localMinutes) + valueToIncrementBy : valueToIncrementBy);
};

You can then call this function to increment the value like this:然后,您可以调用此函数来增加值,如下所示:

updateValuesMinutes(5); // This will update the localStorage value by 5 more than it already is.

Local storage values are usually stored as a string and therefore need to be converted to a number before they can be incremented.本地存储值通常存储为字符串,因此需要先转换为数字,然后才能递增。

localStorage.setItem( 'StoreMinutes', to); 
//convert string to integer
let localMinutes = parseInt(localStorage.getItem("StoreMinutes")); 
localStorage.setItem('localMinutes', localMinutes++)
console.log(localMinutes); 
};

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

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