【问题标题】:How to increment a number in local storage on click?如何在点击时增加本地存储中的数字?
【发布时间】:2018-09-05 12:01:29
【问题描述】:

我阅读了following answer。基本上我有一个button,当我点击它时,它会在我的localStorage 中增加number,并将其设置为span 中的文本:

页面首次加载时:

$("#jikubox span").text(localStorage.length);

点击功能:

$(".save_post").on("click", function() {
  var curId = $(".my_post_id").data("id");
  $("#input_post_id").val(curId);
  localStorage.setItem("attempts", "0");
  var attempts = Number(localStorage.getItem("attempts"));
  localStorage.setItem("attempts", ++attempts);
  $("#jikubox span").text(localStorage.getItem("attempts"));
});

但如果我执行以下操作,我总是会收到 1

console.log(localStorage.getItem("attempts"));

【问题讨论】:

  • 好吧,您将 attempts 设置为 0,然后在您的点击处理程序中将其递增 ...
  • 因为每次单击按钮时,您都会在此行首先将其设置为 0(零)。 localStorage.setItem("attempts", "0");。然后通过增加它,你总是将它设置为 1。
  • @Zenoo 哎哟!没错!

标签: javascript jquery local-storage


【解决方案1】:

您总是在这一行中将 localStorage 值重置为 0:

localStorage.setItem("attempts", "0");

试试这个,检查 localStorage 属性是否未设置,如果未设置,则仅添加默认值 0:

if (!localStorage.attempts) localStorage.attempts = '0';

【讨论】:

  • 哎呀,非常感谢。会接受这个,因为你是第一个
  • 嘿最后一件事,如果本地存储等于 2,我需要停止添加点击,我尝试了 if(localStorage.getItem("attempts") >= 2) { alert("nope"); localStorage.attempts = '2' },但当它变为 2 时我收到警报
  • 这是正确的方法,您可能没有在正确的位置添加代码 - 将它放在处理程序的最顶部。
  • 这样吗? $(".save_post").on("click", function() { if(localStorage.getItem("attempts") >= 2) { alert("nope"); localStorage.attempts = '2' } if(localStorage.getItem("attempts") < 2) { var curId = $(".my_post_id").data("id"); $("#input_post_id").val(curId); if (!localStorage.attempts) localStorage.attempts = '0'; var attempts = Number(localStorage.getItem("attempts")); localStorage.setItem("attempts", ++attempts); $("#jikubox span").text(localStorage.getItem("attempts")); } });
  • 如果你只是在糟糕的情况下提前返回代码会更好看,而不是为主要逻辑创建另一个块:if (localStorage.getItem("attempts") >= 2) { alert('nope'); return; } 然后你不需要下面的另一个 if 块跨度>
猜你喜欢
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多