gpt4 book ai didi

javascript - 页面刷新显示整个本地存储对象

转载 作者:行者123 更新时间:2023-11-29 15:10:56 24 4
gpt4 key购买 nike

我使用 Vanilla Javascript 和 localstorage 构建了一个待办事项列表。待办事项列表具有以下键值:

key: todolist
value: [[\"id:0\",\"title:buy groceries\",\"done:false\"],
[\"id:1\",\"title:pick up dry cleaning\",\"done:false\"],
[\"id:2\",\"title:walk dog\",\"done:false\"]]

这些值在我的网站上显示得很好(仅显示标题)但是当我刷新页面时,整个对象都在显示。

页面刷新前:

  • 买杂货
  • 拿起干洗
  • 遛狗
  • 页面刷新后:

  • id:0,title:买杂货,done:false
  • id:1,title:取干洗,done:false
  • id:2,title:walk dog,done:false
  • 显然,在刷新页面后,我只希望标题显示在 li 标签内的列表中。这是一个令人头疼的问题,因为它仅在页面刷新后执行此操作。

    如何在页面刷新后只显示标题?

    我是 Javascript 的新手,不太明白如何做到这一点。我已经在谷歌上搜索了将近两天,并准备撕掉我的头发!!

    // set up some variables for elements on the page
    const form = document.querySelector('form');
    const ul = document.querySelector('ul');
    const button = document.querySelector('button');
    const input = document.getElementById('item');


    // Fix empty array when script runs by making a conditional statement that
    checks if localStorage already exists

    //let itemsArray = localStorage.getItem('todolist') ?
    JSON.parse(localStorage.getItem('todolist')) : [];

    let todolist;

    if (localStorage.getItem('todolist')) {
    itemsArray = JSON.parse(localStorage.getItem('todolist'));
    } else {
    itemsArray = [];
    }

    localStorage.setItem('todolist', JSON.stringify(itemsArray));
    const data = JSON.parse(localStorage.getItem('todolist'));

    //alert(typeof(data));




    // function that creates an li element, sets the text of the element to the
    parameter, and appends the list item to the ul.
    const liMaker = (text) => {
    const li = document.createElement('li');
    li.textContent = text;
    ul.appendChild(li);


    // Create a "close" button and append it to each list item
    var span = document.createElement("SPAN");
    var txt = document.createTextNode("🗑️");

    span.className = "close";
    span.appendChild(txt);
    li.appendChild(span);

    for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
    var div = this.parentElement;
    div.style.display = "none";
    }
    }
    }


    // Event listener that submits the value of the input
    form.addEventListener('submit', function (e) {
    e.preventDefault();

    var id = "id:" + itemsArray.length;
    var title = "title:" + input.value;
    var done = "done:" + "false";

    itemsArray.push([id, title, done]);
    //itemsArray.push(input.value);
    localStorage.setItem('todolist', JSON.stringify(itemsArray));
    liMaker(input.value);
    input.value = "";
    });

    data.forEach(item => {
    liMaker(item);
    });

    // clear items from todolist
    button.addEventListener('click', function () {
    localStorage.removeItem("todolist");
    while (ul.firstChild) {
    ul.removeChild(ul.firstChild);
    }
    itemsArray = [];
    });

    我应该注意一件事,当我更改以下内容时不会发生页面刷新问题: itemsArray.push([id, title, done]);到以下内容: itemsArray.push(input.value);

    最佳答案

    您遇到此问题的主要原因是您的 JSON 格式不正确。
    您只在页面刷新时看到问题的原因是,此时本地存储包含“todolist”键以及格式不正确的 JSON。然后,此 JSON 值存储在您的 data 变量中,并以不希望的方式(如您所述)输出到您的列表项。

    否则(无需刷新页面)列表项的文本将直接来自输入字段中的文本。

    如果您对代码进行以下更改,它将正常工作(我已经测试过了)。希望对您有所帮助。

    JavaScript 注释

    首先,我不确定这是否是您在此处发布代码时发生的,但是如果您在 JS 中的注释跨越两行或更多行,那么您需要在所有行上放置 //

    例如在你的代码中你有:

    //function that creates an li element, sets the text of the element to the 
    parameter, and appends the list item to the ul.

    应该是:

    //function that creates an li element, sets the text of the element to the 
    //parameter, and appends the list item to the ul.

    JSON 格式

    其次,我发现 JSON 的格式化方式存在问题。它应该类似于以下内容(在添加斜线之前)。

    [{"id":0,"title":"buy groceries","done":false}, 
    {"id":1,"title":"pick up dry cleaning","done":false},
    {"id":2,"title":"walk dog","done":false}]

    注意每个属性名称(即 "id""title""done")应该有双引号和每个属性值(例如 "buy groceries")应该有双引号(除非是 int 或 boolean 等)。您可以使用名为 JSLint 的工具检查您的 JSON 是否有效。

    因此,为了以正确的格式创建您的 JSON(在提交表单时)

    更改这些代码行:

    var id = "id:" + itemsArray.length;
    var title = "title:" + input.value;
    var done = "done:" + "false";
    itemsArray.push([id, title, done]);

    以下内容:

    var idValue = itemsArray.length;
    var titleValue = input.value;
    var doneValue = false;
    itemsArray.push({"id": idValue, "title": titleValue, "done" : doneValue});

    遍历数组

    您的 data 变量将包含 todolist 对象数组(来自本地存储)。

    因此,您在以下代码中拥有的 item 将包含完整对象,即 {"id":0,"title":"buy groceries","done":false }

    因此,为了在此处获得标题,您需要输入 item.title。 (现在 JSON 格式正确,这将起作用):

      data.forEach(item => {
    //log the item to check it.
    console.log(item);
    liMaker(item.title);
    });

    关于javascript - 页面刷新显示整个本地存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544474/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com