【问题标题】:How can i delete one row from a Table, which is saved in localStorage?如何从保存在 localStorage 中的表中删除一行?
【发布时间】:2020-11-21 20:00:01
【问题描述】:

我的问题是,我只能删除完整的内容。通过我需要删除我选择的行。 我试过这个:

function addData(){
    arr.push({
        name:document.getElementById('name').value,
        datum:document.getElementById('datum').value,
        start:document.getElementById('start').value,
        ziel:document.getElementById('ziel').value,
        hinfahrt:document.getElementById('hinfahrt').value,
        ruckfahrt:document.getElementById('ruckfahrt').value,
        zuzahlung:document.getElementById('zuzahlung').value
    }); 

    localStorage.setItem("localData",JSON.stringify(arr)); <---------
}


function deleteOne(){
    var content = localStorage.getItem("localData");
    localStorage.removeItem(JSON.stringify(arr[1]));
    localStorage.removeItem(content);              
}

信息在一个数组中。关键是“localData”。我怎样才能特别针对一行?

检查点标记删除行: Front

编辑

我试图实现,你说什么。但我有这个问题。无法从存储中删除。这是我的完整代码。问题出在方法上 deleteOne() XXX 的值。希望你能理解我的问题。

var rowId = 0;

var testcounter;
function deleteMoreRows(tableID) {

  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var selectedRows = getCheckedBoxes();

  selectedRows.forEach(function (currentValue) {
    deleteRowByCheckboxId(currentValue.id);


  });



}

function getRowId() {
  rowId += 1;
  return rowId;
}

function getRowIdsFromElements($array) {
  var arrIds = [];

  $array.forEach(function (currentValue, index, array) {
    arrIds.push(getRowIdFromElement(currentValue));
  });

  return arrIds;

}

function getRowIdFromElement($el) {
  return $el.id.split('delete')[1];
}


function getCheckedBoxes() {



  var inputs = document.getElementsByTagName("input");
  var checkboxesChecked = [];

  for (var i = 0; i < inputs.length; i++) {
    // And stick the checked ones onto an array...
    if (inputs[i].checked) {


      checkboxesChecked.push(inputs[i]);

    }
  }

  return checkboxesChecked.length > 0 ? checkboxesChecked : null;



}


function deleteRowByCheckboxId(CheckboxId) {
  var checkbox = document.getElementById(CheckboxId);
  var row = checkbox.parentNode.parentNode;                //box, cell, row, table
  var table = row.parentNode;

  while (table && table.tagName != 'TABLE')
    table = table.parentNode;
  if (!table) return;
  table.deleteRow(row.rowIndex);





}

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("search");
  filter = input.value.toUpperCase();
  table = document.getElementById("tbl_id");
  tr = table.getElementsByTagName("tr");
  for (i = 1; i < tr.length; i++) {
    // Hide the row initially.
    tr[i].style.display = "none";

    td = tr[i].getElementsByTagName("td");
    for (var j = 0; j < td.length; j++) {
      cell = tr[i].getElementsByTagName("td")[j];
      if (cell) {
        if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
          break;
        }
      }
    }
  }
}

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("tbl_id");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc";
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      //Each time a switch is done, increase this count by 1:
      switchcount++;
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}


function sortTableByAdding() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("tbl_id");
  switching = true;
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[1];
      y = rows[i + 1].getElementsByTagName("TD")[1];
      //check if the two rows should switch place:
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        //if so, mark as a switch and break the loop:
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}









var arr = new Array();



//form onsubmit
function addData() {
  getData();
  arr.push({
    name: document.getElementById('name').value,
    datum: document.getElementById('datum').value,
    start: document.getElementById('start').value,
    ziel: document.getElementById('ziel').value,
    hinfahrt: document.getElementById('hinfahrt').value,
    ruckfahrt: document.getElementById('ruckfahrt').value,
    zuzahlung: document.getElementById('zuzahlung').value
  });

  localStorage.setItem("localData", JSON.stringify(arr));
  showData();


}

function getData() {
  var str = localStorage.getItem("localData");
  if (str != null) {
    arr = JSON.parse(str);
  }
}








function deleteData() {
  localStorage.clear();
}


function deleteOne() {
  var inhalt = localStorage.getItem("localData");
  var tmp = JSON.parse(inhalt);
  localStorage.removeItem("localData");
  tmp.splice(**XXX**, 1);
  localStorage.setItem("localData", JSON.stringify(tmp));

}


function showData() {
  getData();
  var table = document.getElementById('tbl_id');

  var x = table.rows.length;

  while (--x) {
    table.deleteRow(x);
  }




  for (i = 0; i < arr.length; i++) {
    var inputname = document.getElementById('name').value;
    var inputdatum = document.getElementById('datum').value;
    var inputstart = document.getElementById('start').value;
    var inputziel = document.getElementById('ziel').value;
    var inputhinfahrt = document.getElementById('hinfahrt').value;
    var inputruckfahrt = document.getElementById('ruckfahrt').value;
    var inputzuzahlung = document.getElementById('zuzahlung').value;


    var row = table.insertRow();

    var rowBox = row.insertCell(0);
    var userName = row.insertCell(1);
    var userDatum = row.insertCell(2);
    var userStart = row.insertCell(3);
    var userZiel = row.insertCell(4);
    var userHinfahrt = row.insertCell(5);
    var userRuckfahrt = row.insertCell(6);
    var userZuzahlung = row.insertCell(7);
    var checkbox = row.insertCell(8);

    rowBox.innerHTML = '<input type="checkbox" id="delete' + getRowId() + '">';
    userName.innerHTML = arr[i].name;
    userDatum.innerHTML = arr[i].datum;
    userStart.innerHTML = arr[i].start;
    userZiel.innerHTML = arr[i].ziel;
    userHinfahrt.innerHTML = arr[i].hinfahrt;
    userRuckfahrt.innerHTML = arr[i].ruckfahrt;
    userZuzahlung.innerHTML = arr[i].zuzahlung;

  }


  sortTableByAdding();

}

HTML

<body>
<input id="name" placeholder="Name" size="12" required>
<input id="datum" name="semdate" type="date" required>
<input id="start" placeholder="Start" size="12" required>
<input id="ziel" placeholder="Ziel" size="12" required>
<input id="hinfahrt" type="checkbox">Hinfahrt
<input id="ruckfahrt" type="checkbox">Rückfahrt
<input id="zuzahlung" placeholder="Zuzahlung" size="12">


<br>
<input type="button" id="mysubmit" value="Add" onClick="addData()">
<input type="button" id="delete" value="Delete" 
onClick="deleteMoreRows('tbl_id')">
<input type="text" id="search" onkeyup="myFunction()" placeholder="Suche" 
title="Type in a name">

<br>
<br>
<table id="tbl_id" style="text-align:center" align="center" valign="top">
    <thead>
        <tr>
            <th style="width:200px;">Löschen</th>
            <th onclick="sortTable(1)" style="width:200px;">Name</th>
            <th onclick="sortTable(2)" style="width:200px;">Datum</th>
            <th onclick="sortTable(3)" style="width:200px;">Start</th>
            <th onclick="sortTable(4)" style="width:200px;">Ziel</th>
            <th onclick="sortTable(5)" style="width:200px;">Hinfahrt</th>
            <th onclick="sortTable(6)" style="width:200px;">Rückfahrt</th>
            <th onclick="sortTable(7)" style="width:200px;">Zuzahlung</th>
        </tr>
    </thead>

    <script>
        showData();
    </script>


    <button onclick="deleteData()">!!!Clear Storage!!!</button>


    <button onclick="deleteEinzel()">test</button>

    </body>

【问题讨论】:

    标签: javascript local-storage


    【解决方案1】:

    您可以使用允许您通过键定位值的数据结构。一种选择是使用对象而不是数组,并通过相应的键删除/添加行。

    // pass the id as a parameter to target the row
    function addData(rowId) {
      let storageTmp = JSON.parse(localStorage.getItem("storage"));
      storageTmp = {
        // ... -> spread operator
        // add content of storage
        ...storageTmp,
        // add new row
        rowId: {
          name: 'name',
          datum: 'datum'
        }
      }
      // overwrite storage variable
      localStorage.setItem("storage", JSON.stringify(storageTmp));
    }
    
    // pass the id as a parameter to target the row
    function deleteOne(rowId) {
      const storageTmp = JSON.parse(localStorage.getItem("storage"));
      // remove property 
      delete storageTmp.rowId;
      localStorage.setItem("storage", JSON.stringify(storageTmp));
    }
    

    另一种方法是使用由 ECMA 6 引入的 Map

    【讨论】:

      【解决方案2】:

      将内容保存在 Json 对象中。

       var tmp = JSON.parse(content);
      

      然后删除本地存储的全部内容

       localStorage.removeItem("localdata");
      

      然后删除你的行

       tmp.splice(row, 1);
      

      最后将数据扔到本地存储中

      localStorage.setItem("localData",JSON.stringify(tmp));
      

      【讨论】:

        【解决方案3】:

        您必须从本地存储中检索条目,删除要删除的值,然后再次将其写入本地存储。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-11-27
          • 2018-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-18
          • 2012-09-22
          相关资源
          最近更新 更多