使用js从localstorage移除特定项目 [英] Remove a specific item from localstorage with js

查看:64
本文介绍了使用js从localstorage移除特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向本地存储添加简单的记录,但是我很难从我的本地存储对象中删除特定的项目.我能够保持刷新数据并继续添加记录没有问题.我想在每个条目旁边添加一个按钮,使我可以从本地存储和列表中删除该特定记录.

I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.

鉴于下面的代码,我该如何完成?

How would I accomplish this given the code below?

var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;

// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
    recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
    theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
    recordCounter.innerHTML = (count = 0);
}

function addNameRecord() {

    resetNotify.innerHTML = '';
    var name = document.getElementById('names-field');

    nameArray = JSON.parse(st.getItem('names'));
    count = Number(count) + 1;
    newArr = makeArr(nameArray);

    // Check if there is anything in the name array.
        if (nameArray != null) {
    nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
    nameArray = [];
    nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}

    st.setItem("names", JSON.stringify(nameArray));
    name.value = '';

    if (!newArr[0]) {
        count = 1;
        theLIst.innerHTML = nameArray;
        recordCounter.innerHTML = count;
    } else {
        theLIst.innerHTML = newArr[0].join('');
        recordCounter.innerHTML = count;
    }
}

// Take our string from local storage and turn it into an array we can use
function makeArr() {
    return Array.from(arguments);
}

// Purge all entries, reset counter
function clearArray() {
    st.clear();
    nameArray = [];
    theLIst.innerHTML = '';
    recordCounter.innerHTML = (count = 0);
    resetNotify.innerHTML = 'Array has been purged.';
}

这里是我尝试的代码

    // Delete a specific entry
    function clearThisItem(item) {
        console.log(item);
        localStorage.removeItem(item);
        console.log(localStorage.removeItem(item))
        return item;
    }

推荐答案

此处为重构代码.

  • 首先,无需存储计数,因为我们始终可以访问names.length

  • Firstly there is no need to store count, as we always have access to names.length

仅将名称存储在localStorage上,而不存储整个HTML

Store only names on localStorage, not entire HTML

注意:在以下实现中,将names-field重命名为name-field.

Note: Renamed names-field to name-field in the below implementation.

这是工作代码: https://jsbin.com/simitumadu /1/edit?html,js,输出

var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');

var names = getNames();

if(names == null){
  setNames([]); // initializing the empty array for first time.
}

renderData(); // display data

function addNameRecord() {
    $resetMessage.innerHTML = '';
    var name = document.getElementById('name-field');
    addName(name.value);
    renderData();
    name.value = ''; //clear input field
}

function renderData(){
    var names = getNames();
    $resetCouter.innerText = names.length; // Count
    var namesListHTML = '';
    names.forEach(function(name, index){
      namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
    });
    $list.innerHTML = namesListHTML;
}

function clearArray() {
    setNames([]); // clear names
    $resetMessage.innerHTML = 'Array has been purged.';
    renderData();
}

function clearThisItem(name){
  removeName(name); // remove from localStorage
  renderData();
}

function getNames(){
  namesStr = localStorage.getItem('names');
  if(namesStr) {
    return JSON.parse(namesStr);
  }
  return null;
}

function setNames(names){
  return localStorage.setItem('names', JSON.stringify(names));
}

function addName(name){
  var names = getNames();
  names.push(name);
  setNames(names);
}

function removeName(name){
  var names = getNames();
  var index = names.indexOf(name);
  if (index > -1) {
    names.splice(index, 1);
  }
  setNames(names);
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
  
  <p>Count : <span id="record-counter"></div></p>
  
  <input id="name-field">
  
  <button onclick="addNameRecord()">Add</button>
  
  <button onclick="clearArray()">Clear</button>
  
  <div id="list"></div>
  <div id="reset-message"></div>
  
  
</body>
</html>

这篇关于使用js从localstorage移除特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆