使用js从localstorage中删除特定项目

时间:2018-05-23 01:18:39

标签: javascript local-storage

我正在向localstorage添加简单记录,但是我很难从localstorage对象中删除特定项目。我能够在刷新时保持数据并继续添加记录没问题。我想在每个条目旁边添加一个按钮,允许我从localstorage和我的列表中删除该特定记录。

如果给出以下代码,我将如何实现这一目标?

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;
    }

2 个答案:

答案 0 :(得分:2)

这是重构的代码。

  • 首先不需要存储计数,因为我们总是可以访问names.length

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

  • 要添加和删除名称,请从localStorage获取名称数组,更新它并将其保存回localStorage。
  • 每次操作后,只需使用一个函数调用即可更新UI。

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

以下是工作代码:https://jsbin.com/simitumadu/1/edit?html,js,output

&#13;
&#13;
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);
}
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用 localStorage.removeItem(insertYourKeyHere); 从本地存储中删除对象。
要从nameArray中删除它,您可以在列表中搜索记录,设置为null,然后通过确保将对象移动到新位置以使null结束,然后减少记录数量的计数来对列表进行排序