【问题标题】:LocalStorage data appearing in console but not in the DOMLocalStorage 数据出现在控制台中但不在 DOM 中
【发布时间】:2020-09-11 06:38:24
【问题描述】:

我目前正在构建一个待办事项列表应用程序,并且我已经使用 localStorage API 保存了数据。

然而,每当我 console.log 时,所需的数据就会出现在控制台中,但它仍然没有保存在 DOM 中。

我还添加了getItem() 函数并将其登录到控制台,我仍然可以在控制台中查看它,请在此处找到: getItem content in the console

但它只是不存储在浏览器中

看到这一点,您倾向于认为它应该存储在 DOM 中,并且在重新加载后内容仍然存在,但这里的情况并非如此。

下面的这个函数在列表中添加一个新项目,它也删除和划掉已完成的项目:

let id = 0;
function addTaskFunc() {

    const aTask = `
    <div class="task" id="task-${id}">
        <button class="done__btn">
            <i class="far fa-check-square"></i>
        </button>
        <p>${box.value}</p>
        <button class="priority">Make priority</button>
        <button class="cancel__btn">
            <i class="far fa-times-circle"></i>
        </button>
    </div>
`;


    const x = box.value;
    if (x) {
        taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';
        ;

        let cid = id;

        const cancelBtn = document.querySelector(`#task-${id} .cancel__btn`);
        cancelBtn.addEventListener('click', () => {
        deleteItem(cid);
        });

        let cid2 = id;

        // code for marking out an item as done

        let cid3 = id;

        // code for appending an item to the top of DOM

        let cid4 = id;
        persistData(cid4);
        readData(cid4);
        id++;  
    }
}

newTask.addEventListener('click', addTaskFunc); // Button to activate the function

persistData = id => {
    const el = document.querySelector(`#task-${id}`);
    localStorage.setItem('addedTasks222', el.innerHTML);

};

readData = id => {
    const el = document.querySelector(`#task-${id}`);
    const saved = localStorage.getItem('addedTasks222');
    if (saved) el.innerHTML = saved;
    console.log(el.innerHTML); // This line of code appears in the console
}

我也尝试在 addTaskFunc 中这样做:

const r = document.querySelector(`#task-${id} .task`);
r.addEventListener('load', () => {
          persistData(cid4);
          readData(cid4);
 });

当我使用上面的方法尝试时,我在控制台中得到错误代码: 无法读取 null 的 addEventListener 的属性。

我觉得某处有问题,但我似乎无法找出我错过的地方。

最后一件事,localStorage 似乎只将一项存储到密钥中。我需要一个循环来解决这个问题吗?

【问题讨论】:

    标签: javascript html function local-storage insertadjacenthtml


    【解决方案1】:

    你可以像这样在本地存储中存储一个数组

    localStorage.setItem('array', JSON.stringify(YOURARRAY))

    然后你可以加载它

    var restoreArray = JSON.parse(localStorage.getItem('array'));

    【讨论】:

    • 非常感谢您的回复。那么使用您的解决方案,它会保存数据并在刷新后仍然显示?这个解决方案似乎只是将解决方案保存到数组中而不是解决实际问题。
    • 你是说它没有出现在 DOM 中的原因是因为我没有将它存储在数组中吗?
    • 我正在查看您的代码,问题是:您正在使用函数 persistData 重置数据,然后每次刷新页面时将空数据存储到 localStorage。您首先需要使用 (readData) 读取本地存储。只有在内容发生变化时才需要运行persistData函数。
    • Pereira,现在我遇到了另一个问题,它说它不能将属性“innerHTML”设置为空。我应该创建一个 JSFiddle 以便您查看它吗?
    【解决方案2】:

    对不起。。 所以我正在查看您的代码,并且似乎您有一些问题.. 1- 我看到的第一个是在 persistData() 函数中。不小心你只是选择了一个任务来存储 document.querySelector(.task); 选择所有你需要使用 document.querySelectorAll(.task),这将返回一个数组。因此,您只存储一项任务。 2-其次是您正在尝试存储 html。使用.innerHtml,并且您的(“.class”)的innerHtml 是按钮等。您应该存储值。 3-最后,当您尝试打印数据时,您执行 document.querySelector(.task),并且您可以看到它返回未定义,那是因为您还没有 .task div。

    那么您如何才能适当地使您的应用正常运行。

    1- 你需要做的第一件事是在你的 js 文件上创建一个数组变量。

    让任务 = [];

    2-该数组将用于存储您的任务的值,如下所示

        function addItem(){
          let value = item.value; //you need to define the item some way
          tasks.push(value);
          print() //a function to print the values;
          persistData() // store the array
        }
    

    3-打印任务

        function print(){
          tasks.forEach(task => {
           let div = document.createElement("div");
           div.innerHTML = `copy your html task to here, use ${task} to print the task value`
          })
        }
    

    4-存储任务

    function persistData(){
       localStorage.setItem('addedTasks', tasks); //store the array
    };
    
    function readData(){
       if (typeof(Storage) !== "undefined") { //check if the browser has localStorage 
        tasks = localStorage.getItem('addedTasks'); //update your array
        print();
       } else {
        //No Web Storage message
       }
    };
    

    5- 加载文档时只需运行 readData()

     document.addEventListener("DOMContentLoaded", function(event) {
          readData();
      });
    

    希望能帮到你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2018-03-23
      • 2022-01-04
      相关资源
      最近更新 更多