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

Posted

技术标签:

【中文标题】从本地存储中检索数据不起作用【英文标题】:Retrieving data from local storage not working 【发布时间】:2018-04-26 00:54:51 【问题描述】:

我可以保存到本地存储,但是当我添加代码来检索数据时它不起作用。我可以看到代码已保存,因为我在 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];
    )

);

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

【问题讨论】:

【参考方案1】:

问题在于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>

因此,循环索引 (i) 永远不会超过 1 - 0 代表“史蒂夫”的单元格,1 代表史蒂夫出生日期的单元格。然后循环结束,因为没有更多的单元格:

// 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数组中的前两个值替换——stevesteve替换,13/12/195613/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];
    );
  

Working example on Codepen(试图在此处发布,但localStorage 在 SO sn-ps 中不起作用)

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

【讨论】:

感谢您详细解释问题所在并提供解决方案。 Codepen 示例也非常有用。再次非常感谢。【参考方案2】:

正如@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>');
        

    

【讨论】:

感谢您向我展示了解决此问题的另一种方法,非常感谢。再次感谢。

以上是关于从本地存储中检索数据不起作用的主要内容,如果未能解决你的问题,请参考以下文章

从phpMyAdmin数据库中检索数据不起作用[关闭]

我的共享首选项存储列表视图的数据并检索它不起作用

从视图中检索数据的查询不起作用

从 UTC 转换为本地时,夏令时在 TimeZoneInfo 中不起作用

从核心数据中检索 UUID 并设置 UUID 变量不起作用

离子本机存储: storage.getItem() 不起作用[重复]