如何在点击时增加本地存储中的数字?

时间:2018-03-27 07:27:45

标签: javascript jquery local-storage

我读了following answer。基本上我有button,当我点击它时,它会增加number中的localStorage,并将其设置为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"));

1 个答案:

答案 0 :(得分:4)

您始终在此行中将localStorage值重置为0:

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

请尝试此操作,检查localStorage属性是否未设置,如果未设置,则仅添加默认值0:

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