【问题标题】:How to update Value of a TODO List from browser Local Storage every time i reload the page?每次重新加载页面时,如何从浏览器本地存储中更新 TODO 列表的值?
【发布时间】:2020-07-17 09:42:19
【问题描述】:

我创建了这个任务列表项目,用户可以在其中添加和删除任务。我还添加了将任务列表值保存到浏览器本地存储的功能,因此当页面重新加载时,列表项仍然保留在页面上。我面临的问题是此功能仅适用于隐身选项卡或当我硬重新加载正常选项卡时。我认为这是一些与缓存相关的问题。?

有没有什么方法可以在不重新加载且不打开隐身标签的情况下检索列表?

下面是相同的 HTML、CSS 和 JAVASCRIPT 代码。

//Here we select the input whose value will be the name of new create list whithin list container.
var addItemBtn=document.querySelector('input[type="submit"]');
//Here we select the add button that adds the the value of above input to list container.
var inputItemName=document.querySelector('input[type="text"]');
//Trigger an click event when we click the add buttton and call addListItem() function.
addItemBtn.addEventListener('click',addListItem);
//Here we select the list container.
var listContainer=document.getElementById('listContainer');
//Declare an object storing the list-item content and its corresponding count number.
    function addListItem(ev)
    {
        //This prevents the data of list from deleting when the function finishes its work.
        ev.preventDefault();
        //Check if the input field is empty or spaced or null
        if(inputItemName.value=="" || inputItemName.value==" "  )
        {
            //Display an error message on the webpage.
            document.getElementById('errorMessage').innerHTML='<img src="error-image.jpg" class="error-img" alt="Hindustani Bhau"/>'+'Please Enter Some Value In The Text-Box.';
        }
        else
        {
            
            //Remove the error message from the page.
            document.getElementById('errorMessage').innerHTML='';
            //Directly create the list items in innerHTML of listcontainer and increment it everytime.
            listContainer.innerHTML+=
            `<li class="listItem">
            ${inputItemName.value}
                <button class="closeBtn" onclick="removeListItem(this)">X</button>
            </li>
            `;
            
                //Store the contents of listContainer in local storage directly.
                localStorage.myListItems = listContainer.innerHTML;
           
            
            //Clear the input when we add a item.
            inputItemName.value='';
        }
        
    }
    
   
    //Function to remove the selected list item
    function removeListItem(e)
    {
        if(confirm('Are you sure you want to do this ?'))
        {
            //Deletes the parent li element of the given child node close button.
            e.parentNode.style.display='none';
        }
    }
        //When the body loads just append all values stored in local storage to the listContainer.
        document.body.onload=()=>
        {
            if(localStorage.getItem('myListItems')!=undefined)
            {
                //Retrieve data from local storage.
            listContainer.innerHTML=localStorage.myListItems;
            console.log("Item Persists");
            }
                
            
            
        }
*
{
    padding:10px;
    margin:0px;
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif ;
}
.main-heading
{
    text-align: center;
    font-size: 5rem;
    width:100%;
    font-weight:lighter;
    color:#00bf8f;
}
#mainList
{
    min-height:500px;
    width:500px;
    margin:3rem auto;
    padding:30px;
    box-shadow:0px 0px 8px 0px #000;
}
.inputListName
{
    margin:1rem auto;
    min-width:100%;
}
.inputListName > .addItemHeading
{
    text-align:center;
    font-size:2rem;
    font-weight: lighter;
    color:#00bf8f;
}
.inputListName > hr
{
    border:1px solid #00bf8f;
    width:100px;
    padding:0px !important;
    margin:1rem auto;
}

.inputListName > input[type="text"]
{
    height:45px;
    width:65%;
    font-size: 1rem;
    float:left;
    text-align:center; 
    color:#00bf8f;
    font-weight: bolder;
    border:1px solid #0b8793;
    border-radius:10px; 
}
.inputListName > input[type="text"]:focus
{
    box-shadow:0px 0px 8px 0px #0009;
}
.inputListName > input[type="submit"]
{
    height:45px;
    width:30%;
    margin-left:10px;
    float:left;
    border:1px solid #0b8793;
    background:white;
    color:#0b8793;
    border-radius:10px;
    font-size: 1rem;   
}
.inputListName > input[type="submit"]:hover
{
    color:white;
    background:#0b8793;
}
#errorMessage
{
    color:#c31432;
    position: relative;
    top:10px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
}
.error-img
{
    height:80px;
    width:80px;
    border-radius: 20px;
}
#listContainer
{
    counter-reset: section;
}
 #listContainer > li
{
    list-style-type: none;
    width:100%;
    position: relative;
    padding:15px;
    height:52px;
    margin-top:10px;
    border:1px solid #00bf8f;
    color:#00bf8f;
    font-weight: bolder;
}
#listContainer > li::before {
    counter-increment: section;
    content: counter(section) ": ";
    color:#00f260;
  }
#listContainer > li >.closeBtn
{
    position: absolute;
    right:0;
    top:0;
    color:red;
    border:none;
    height:50px;
    width:40px;
    font-weight: bolder;
    text-align: center;
    background:#00f260;
}
#listContainer > li:hover
{
    background:#00bf8f;
    color:#fff;
}
footer >h4
{
    text-align: center;
    background-color: #00bf8f;
    color:#fff;
    min-height:40px;
}

@media only screen and (max-width:500px)
{
    #mainList
    {
        width:100%;
    }
}
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv='cache-control' content='no-cache'>
        <meta http-equiv='expires' content='0'>
        <meta http-equiv='pragma' content='no-cache'>
        <title>My First TODO List.</title>
        <link rel="icon" href="app-icon.png"/>
        <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
        <link rel="stylesheet" href="style.css"/>
         <!--Web app manfest file for android devices-->
        <link rel="manifest" href="manifest.json" />
        <meta name="theme-color" content="#dd62ff" />
    </head>
    <body>
        <h1 class="main-heading">TODO List</h1>
        <div class="list" id="mainList">
            <form class="inputListName" name="form-input" accept="index.html" >
                <h4 class="addItemHeading">Add Items To The List</h4>
                <hr/>
                <input type="text" class="inputName" placeholder="Type Task name"/>
                <input type="submit" class="submitName" value="Add"/>
                <p id="errorMessage"></p>
            </form>
            <div id="deleteAllListItem"></div>
            <ul id="listContainer"></ul>
        </div>
        <footer>
            <h4>This TODO List is Made With &hearts; By Vaibhav Kaul</h4>
        </footer>
    </body>
    <script>
        //Check if the service worker exists in the navigator object.
        if ("serviceWorker" in navigator) 
    {
        window.addEventListener("load", function() 
        {
        navigator.serviceWorker
            .register("service-worker.js")
            .then(res => console.log("service worker registered"))
            .catch(err => console.log("service worker not registered", err))
        })
    }
  </script>
    <script src="app.js"></script>
</html>

【问题讨论】:

    标签: javascript html css caching


    【解决方案1】:

    请先控制台 让存储 = localstorage.getitem("myListItems") 控制台日志(存储) 然后代表那个结果采取行动

    【讨论】:

    • 感谢您的帮助,但一切正常,但只有当我重新加载页面时。正常重新加载不会让浏览器从本地存储中获取数据。?
    • 是的,我认为存在异步问题,因此请确保在数据存在时进行渲染。通过使用 if 条件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多