簡體   English   中英

如何從保存在 localStorage 中的表中刪除一行?

[英]How can i delete one row from a Table, which is saved in localStorage?

我的問題是,我只能刪除完整的內容。 我需要刪除我選擇的一行。 我試過這個:

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>

您可以使用允許您按鍵定位值的數據結構。 一種選擇是使用對象而不是數組並通過相應的鍵刪除/添加行。

// 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

將內容保存在 Json 對象中。

 var tmp = JSON.parse(content);

然后刪除本地存儲的全部內容

 localStorage.removeItem("localdata");

然后刪除你的行

 tmp.splice(row, 1);

最后將數據扔到本地存儲

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

您必須從本地存儲中檢索條目,刪除要刪除的值,然后再次將其寫入本地存儲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM