繁体   English   中英

从本地存储检索数据不起作用

[英]Retrieving data from local storage not working

我可以保存到本地存储,但是当我添加代码以检索数据时,它不起作用。 我在chrome中使用F12检查时看到代码已保存。 任何指导将不胜感激。

 <!DOCTYPE html>
 <html>
 <head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" 
 href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
 <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-
 1.4.5.min.js"></script>
 </head>
 <body>
 <form>
 <input type="text" id="task" placeholder="name">
 <input type="text" id="date" placeholder="dd/mm/yyyy">
 <input type="button" class="add-row" value="Add Row">

 </form>
 <table id="task_table">
 <thead>
    <tr>
        <th>Name</th>
        <th>Date</th>
    </tr>
 </thead> 
 <tbody>
    <tr>
        <td>steve</td>
        <td>13/12/1956</td>
    </tr>

 </tbody>

 </table>
 <button id="saveAll">Save List</button>


 <script>$("#saveAll").click(function(e) {


 var listBirthdays = [];
 $("table td").each(function(){
   listBirthdays.push(this.innerHTML);
 })
 localStorage.setItem('birthdayList', JSON.stringify(listBirthdays));
 });

 </script>


 <script>
 $(document).ready(function(){
 $(".add-row").on('click',function(){
    var task = $("#task").val();
    var date = $("#date").val();
    var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
    $('table tbody').append(markup);

 });


            }
     );

;


</script>

下面显示了我尝试用来从存储中重新加载数据的代码。

loadList();

function loadList() {
if (localStorage.getItem('birthdayList')){ 
    var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));
    $("table td").each(function(i){
      this.innerHTML = listBirthdays [i];
    })
}

}});

当我添加应检索数据的代码时,它不会将其添加回表中。

问题出在您的loadList函数中的.each循环中。

假设存储的值如下所示:

'["steve", "13/12/1956", "jane", "04/04/1987", "peter", "01/03/1999"]'

它被解析并加载到listBirthdays数组中:

console.log(listBirthdays[0]) // -> "steve"
console.log(listBirthdays[1]) // -> "13/12/1956"
console.log(listBirthdays[2]) // -> "jane"
                              //     …etc.

然后, .each循环在表单元格上运行:

$("table td").each(function(i){ … });

…但是表主体仍然只是带有两个单元格的一行:

<td>steve</td>
<td>13/12/1956</td>

因此,对于具有“ steve”的单元格,循环索引( i )永远不会超过1 – 0,对于具有Steve生日的单元格,循环索引( i )永远不会超过1 – 0。 然后循环结束,因为没有更多的单元格:

// i = 0
this.innerHTML = listBirthdays[0]; // listBirthdays[0] = "steve"

// i = 1
this.innerHTML = listBirthdays[1]; // listBirthdays[1] = "13/12/1956"

// 'i' will never get to 2 as there are no more cells, listBirthdays[2] (and further) will never be used

单元格内容替换为listBirthdays数组中的前两个值– steve替换为steve13/12/1956替换为13/12/1956 因此,看起来什么都没有发生。

一个简单的解决方案是在将数据加载到表中之前添加所需的空行/单元格:

function loadList() {
  if (localStorage.getItem("birthdayList")) {
    var listBirthdays = JSON.parse(localStorage.getItem("birthdayList"));
    // calculate how many rows we need:
    var newRows = listBirthdays.length / 2; // for 2 columns
    // replace tbody content with the new rows:
    $("tbody").html("<tr><td></td><td></td></tr>".repeat(newRows));
    // table now has two cells for each name–date pair
    $("tbody td").each(function(i, cell) {
      cell.innerHTML = listBirthdays[i];
    });
  }
}

Codepen上的工作示例 (试图在此处发布,但是localStorage在SO代码段中不起作用)

但是,更合乎逻辑的方法是基于数据而不是相反地呈现单元。

正如@helb已经解释了您的代码问题。 有另一种解决方法,只需将您的loadList函数更改为:-

 function loadList() {


    if (localStorage.getItem('birthdayList')) {

        var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));

        $("#task_table").find("tr").remove();

        for (i = 0; i < listBirthdays.length - 1; i = i + 2) {
            $('#task_table tbody').append('<tr>' + '<td>' + listBirthdays[i] + '</td>' + '<td>' + listBirthdays[i + 1] + '</td>' + '</tr>');
        }

    }
}

暂无
暂无

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

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