简体   繁体   English

如何在localStorage中添加和删除项目?

[英]How to add and remove items in localStorage?

I am trying to build a logic where we click a button and save an ID in localStorage. 我正在尝试构建一个逻辑,我们单击一个按钮并在localStorage中保存一个ID。 We could have 2 ids max. 我们最多可以有2个。 However, we can also remove an ID from it and add a new one. 但是,我们也可以从中删除ID并添加新ID。 Finally, we cannot add more than 2 and these ids must be unique. 最后,我们不能添加超过2个,这些ID必须是唯一的。 These IDs will be then set as an input value in a form. 然后将这些ID设置为表单中的输入值。

So I have four steps page: 所以我有四个步骤页面:

  • Homepage page 主页
  • Search result page 搜索结果页面
  • Single article page 单篇文章页面
  • Form result page 表格结果页面

Each page has: 每个页面都有:

<form id="post_form_id" method="post" action="/test/compare/"> 
   <input id="input_post_id" type="hidden" name="varPostId" value=""> 
   <button type="submit" class="btn btn-link nav-link" id="jikubox"></i> 
   <span class="badge badge-secondary">0</span></button>
</form>

Saved IDs will be set in name="varPostId" value="" 保存的ID将在name="varPostId" value=""

Now the tricky part which is confusing me, so localStorage can only have strings so first of all on each page load I do: 现在这个棘手的部分令我感到困惑,所以localStorage只能在每次加载页面时都有strings

var lines = localStorage.getItem("lines") ? 
JSON.parse(localStorage.getItem("lines")) : [];

Then since in the article page I have a save button to add the current article id in the array, I do: 然后,因为在文章页面中我有一个save button来添加数组中的当前文章ID,我这样做:

<button type="button" class="save_post">SAVE</button>

JS JS

$(".save_post").on("click", function(e) {
  e.stopImmediatePropagation();
  if (localStorage.getItem("attempts") >= 2) { 
    alert('nope'); 
    return; 
  } else {

  // Here I set the id for each article which I saved before via php in a span 
    var thisId = $(".my_post_id").attr("data-id");

    var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; 
    lines.push(thisId);
    localStorage.setItem("lines", JSON.stringify(lines));
    console.log(lines);
    $("#input_post_id").val(JSON.parse(localStorage.getItem("lines")));
    var attempts = Number(localStorage.getItem("attempts"));
    localStorage.setItem("attempts", ++attempts);
    console.log(localStorage.getItem("attempts"));
    $("#jikubox span").text(localStorage.getItem("attempts"));
  }
});

Notice I have another localStorage: attempts , that is used to add or remove a number I set in a counter badge, basically an indicator which tells how many items I have in my " bag ". 注意我有另一个localStorage: attempts ,用于添加或删除我在计数器徽章中设置的数字,基本上是一个指示器,告诉我在“ ”中有多少项目。 Remember: max 2 and unique. 记住:最大2和唯一。

So finally on the form result page I have a button to remove added items and the following js is used: 所以最后在表单结果页面上我有一个按钮来删除添加的项目,并使用以下js:

$(".removeJiku").on("click", function(){

  // Here I set the id for each article, I do that with php
  // <span  class="removeId" data-thisPostId="<?php echo $idThisPost; ?>"></span>

  var removeThisId = $(".removeId").attr("data-thisPostId");
  $(this).parent().fadeOut();
  var attempts = Number(localStorage.getItem("attempts"));
  localStorage.setItem("attempts", --attempts);
  $("#jikubox span").text(localStorage.getItem("attempts"));
  lines.splice($.inArray(removeThisId, lines), 1);
  localStorage.getItem("lines", lines); 
  localStorage.setItem("lines", lines); 
  console.log(localStorage.getItem("lines"));
});

The logic is kinda ok but after I try few times, I eventually get empty lines array and the ids are not set to the input value . 逻辑有点好,但在我尝试几次之后,我最终得到空lines array ,并且id没有设置为input value I think I over complicated the logic and I was wondering where and how I could simplify and correct it. 我认为我过于复杂的逻辑,我想知道在哪里以及如何简化和纠正它。 I am looking into a single general bit of code which handles all of this without complicating the logic. 我正在研究一个通用的代码,它可以处理所有这些,而不会使逻辑复杂化。

UPDATE UPDATE

Thanks to an answer, one bit of code has been simplified and the counter will be set by checking the length of the ids in lines array so We can remove the whole code for the attempts local storage logic 感谢答案,简化了一些代码,并通过检查lines array中的ID长度来设置counter ,这样我们就可以删除 attempts local storage逻辑的整个代码

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

Assume you store your IDs in an array- 假设您将ID存储在数组中 -

var idList=["123","456"];

You can store IDs like this - 你可以存储这样的ID -

localStorage.setItem("idList",JSON.stringify(idList));

and fetch idList like this- 并获取像这样的idList-

JSON.parse(localStorage.getItem("idList")).length

Just make sure to put validations all around. 只需确保全面验证。

PS No need to count the "attempts" as you can anytime use the below code to find the length of the idList, which can be 2 or any number you want PS无需计算“尝试”,因为您可以随时使用以下代码来查找idList的长度,可以是2或任何您想要的数字

JSON.parse(localStorage.getItem("idList")).length

UPDATE: 更新:

To remove IDs- 删除ID-

function removeId(array, element) {
    const index = array.indexOf(element);
    array.splice(index, 1);
}

Fetch array from localStorage and pass it into this function - 从localStorage获取数组并将其传递给此函数 -

idList  = JSON.parse(localStorage.getItem("idList"))

and call the function like this - 并调用这样的函数 -

 removeId(idList,idToBeDeleted)

This block isn't doing what you want: 这个块没有做你想要的:

lines.splice($.inArray(removeThisId, lines), 1);
localStorage.getItem("lines", lines); 
localStorage.setItem("lines", lines); 

The second line is getting something from localStorage but isn't doing anything with it. 第二行是从localStorage获得一些东西,但没有做任何事情。 It could be the equivalent of 它可能相当于

lines.splice($.inArray(removeThisId, lines), 1);
['one line', 'another line'];
localStorage.setItem("lines", lines);

Just some random value that proceeds to get ignored by the interpreter. 只是一些随机值会被解释器忽略。

The other problem is that you're setting localStorage.lines to the plain lines variable, not to JSON.stringify(lines) . 另一个问题是你将localStorage.lines设置为plain lines变量, 而不是 JSON.stringify(lines)

Note that you can simplify your syntax noise just by doing 请注意,只需执行操作即可简化语法噪音

localStorage.lines = JSON.stringify(lines);

and

const lines = JSON.parse(localStorage.lines || '[]');

localStorage.getItem('item') only accepts one parameter, which will return the value if it exists in the local storage and will return null item doesn't exist. localStorage.getItem('item')只接受一个参数,如果该值存在于本地存储中并且将返回null项不存在,则返回该值。

localStorage.setItem(item, value) accepts two parameters. localStorage.setItem(item, value)接受两个参数。 item which is a key and the value which is to be saved for the key. 作为键的项和要为键保存的值。 If item is already set it will overwrite the value. 如果已设置项目,则将覆盖该值。

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

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