Javascript 重新加载页面后,将值保留在文本框中

Javascript 重新加载页面后,将值保留在文本框中,javascript,html,css,ajax,Javascript,Html,Css,Ajax,我正在为一个课程项目复制一个杂货店网页,我想知道即使在网页刷新后如何在数量框中保留该值 <button type="button" id="subtract" onclick="decrease()">-</button> <input class="quantity-box" type="text" id="text" value=&

我正在为一个课程项目复制一个杂货店网页,我想知道即使在网页刷新后如何在数量框中保留该值

   <button type="button" id="subtract" onclick="decrease()">-</button>
   <input class="quantity-box" type="text" id="text" value="0">
   <button type="button" id="add" onclick="increase()">+</button>
-
+

函数减少(){
var textBox=document.getElementById(“文本”);
如果(textBox.value>0){
textBox.value--;
}
}
功能增加(){
var a=1;
var textBox=document.getElementById(“文本”);
textBox.value++;
}
注意:我能够使用AJAX,但我不熟悉这一点,因此,如果解决方案中包含AJAX,那么简单的解释就足够了。
HTML/JAVASCRIPT/CSS/AJAX

您可以使用cookies,创建两个设置和获取cookies的函数,然后使用它们设置cookies中的数量值,您必须在加载网页时获取数量cookie,因为即使页面重新加载,您也需要设置数量值

下面是一个关于如何实现你想做的事情的例子。 干杯
window.onload=function(){
document.getElementById(“文本”).value=getCookie(“数量”);
}
函数减少(){
var currentValue=document.getElementById(“文本”).value;
如果(当前值>0){
document.getElementById(“text”).value=--currentValue;
setCookie('quantity',currentValue);
}
}
功能增加(){
var currentValue=document.getElementById(“文本”).value;
currentValue=currentValue?currentValue:0;
document.getElementById(“text”).value=++currentValue;
setCookie('quantity',currentValue);
}
函数setCookie(名称、值){
var d=新日期();
var days=10;//在天内过期
d、 设置时间(d.getTime()+(天*24*60*60*1000));
var expires=“expires=“+d.toutString();
document.cookie=name+“=”+value+”;“+expires+”;path=/”;
}
函数getCookie(名称){
变量名称=名称+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);

对于(var i=0;i,您也可以使用localStorage

function decrease(){
  var textBox = document.getElementById("text");
  if (textBox.value > 0){
    textBox.value--;
    localStorage.setItem('quantity', textBox.value);
  }
}

function increase(){
   var a = 1;
   var textBox = document.getElementById("text");
   textBox.value++;
   localStorage.setItem('quantity', textBox.value);
}

window.onload = function() {
  var textBox = document.getElementById("text");
  textBox.value = localStorage.getItem('quantity');
}

本地存储可能是一种可能性,非常感谢!非常感谢!
function decrease(){
  var textBox = document.getElementById("text");
  if (textBox.value > 0){
    textBox.value--;
    localStorage.setItem('quantity', textBox.value);
  }
}

function increase(){
   var a = 1;
   var textBox = document.getElementById("text");
   textBox.value++;
   localStorage.setItem('quantity', textBox.value);
}

window.onload = function() {
  var textBox = document.getElementById("text");
  textBox.value = localStorage.getItem('quantity');
}