页面重新加载后保持文本框中的值

4
我正在为一门课程项目复制一家杂货店网页,并想知道如何在网页刷新后保持数量框中的值。
   <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>

<script>

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


function increase(){
              var a = 1;
              var textBox = document.getElementById("text");
              textBox.value++;
}
</script>

注意:我能够使用AJAX,但对此并不熟悉,如果在解决方案中包含它,简要的说明就足够了。 HTML/JAVASCRIPT/CSS/AJAX

2
本地存储可能是这里的一个选择 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage - Alex D
2个回答

1

同时,您可以使用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');
}

0

你可以使用cookies,在代码中创建两个函数用于设置和获取cookies,然后利用它们来设置数量的值在cookies中。在加载网页时,需要获取数量cookie,即使页面重新加载,也需要设置数量的值。

here is an example about how can you achieve what you want to do. cheers...

window.onload = function(){
  document.getElementById("text").value = getCookie("quantity");
}

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

function increase() {
  var currentValue = document.getElementById("text").value;
  currentValue = currentValue? currentValue: 0;
  document.getElementById("text").value = ++currentValue;
  setCookie('quantity', currentValue);
}


function setCookie(name, value) {
  var d = new Date();
  var days = 10; // expires in days
  d.setTime(d.getTime() + (days*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

function getCookie(name) {
  var name = name + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
<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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接