【问题标题】:How to reload page without losing any data如何在不丢失任何数据的情况下重新加载页面
【发布时间】:2021-09-03 13:51:43
【问题描述】:

我是 Web 开发的新手,我正在制作这个小项目,它包含在一个小网站中,允许用户添加和删除他们的目标(有点像待办事项列表) 我想实现最后一个功能,允许浏览器保存页面的内容,这样如果用户重新加载页面,他/她就不会忘记他们的目标。我尝试使用本地存储,但它不起作用。

关于如何解决此类问题的任何建议/提示? 非常感谢您,我提前为代码异味道歉。

var i = 0
 var j =0
 var parentElement = document.getElementById('new-goals')

 function addGoal(){
        var userGoal = window.prompt('Enter goal: ')
        var divTag = document.createElement('div')
        divTag.className = 'goalsSection'
        divTag.id = 'goal- ' + i
        i++
        var goal = document.createElement('p')
        goal.innerHTML = userGoal
        goal.className= 'usergoal'
        goal.id = 'UserGoal'+j
        

        var del = document.createElement('button')
        del.className = 'deleteButton'
        del.innerHTML = 'Delete Goal'
        del.id = j
        
        var com = document.createElement('button')
        com.className = 'completedButton'
        com.innerHTML = 'Not Completed'
        com.id = j
        j++

        
    
        com.onclick = function(e){

            if (com.innerHTML == 'Not Completed' ){
                var dec = window.prompt('Are you sure? this action can not be undo type y/n')
            if (dec == 'y'){
                com.innerHTML = 'Completed'
                var ele = e.target.id
                    var fin = 'UserGoal'+ele
                    document.getElementById(fin).style.textDecoration='line-through'
                
            }
    
         }

        }
        
       

        divTag.appendChild(goal)
        divTag.appendChild(del)
        divTag.appendChild(com)
        parentElement.appendChild(divTag)
        del.onclick = function(e){
            var id_toDelete = e.target.id
            var id_section = 'goal- ' + id_toDelete 
            alert(id_section)
            parentElement.removeChild(divTag)
        }
        

    }

    
body{
  background-color: #003f5c;
}

h1{
  display: flex;
  justify-content: center;
  font-size: 60px;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.btnConatiner{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
}

#newGoalBtn{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 50px;
  font-size: 30px;
  border-radius: 15px;
  border: solid 5px black;
  cursor: pointer;
}

.goalsSection{
  border: solid 6px white;
  width: 200px;
  height: 100px;
  border-radius: 20px;
 background-color: white;
 margin: 10px;
 float: left;
}

.usergoal{
  text-align: center;
  font-size:20px;
}

.deleteButton{
  cursor: pointer;
}
.completedButton{
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
   
    <title>Goal Tracker</title>
</head>
<body>
    <h1>Goal Tracker</h1>
<div class="btnConatiner">
    <button id="newGoalBtn" onclick="addGoal()">New Goal</button>
</div>
 <section class="add-goals">
<div id="new-goals">

</div>
 </section>
 <script src="app.js"></script>  
</body>

</html>

【问题讨论】:

  • 非常感谢你们的 cmets,我开始掌握它的窍门

标签: javascript html web local-storage reload


【解决方案1】:

您可以使用 localStorage,但不能存储您正在创建的所有 HTML,而是存储基本数据。根据这些数据,您可以轻松地重建您的 html。

首先跟踪您的数据,并设置您的 addGoal 函数以接受重建参数(页面刷新后)

let userGoals = [] // leave this empty for the moment
function addGoal(userGoal){
  if (!userGoal) { // this is a new one, so we'll store it in the array and localStorage
    userGoal = window.prompt('Enter goal: ')
    userGoals.push(userGoal);     
    localStorage.setItem('userGoals', JSON.stringify(userGoals)); // localStorage stores everything as strings so we stringify it
  } 
  //... the rest of this function

然后在脚本底部创建一个window.onload 函数,该函数在页面首次加载时运行一次。如果localStorage 中有数据,这将创建您的用户目标列表

window.onload = function() { // this runs after the page has loaded
  if (localStorage.getItem('userGoals') ) { // if we have localStorage values waiting for us, parse them and iterate through them
    JSON.parse(localStorage.getItem('userGoals')).forEach(goal => {
       userGoals.push(goal)
       addGoal(goal)
     });
  }
}

...

【讨论】:

    【解决方案2】:

    在addGoal函数内部,可以获取本地存储中已经存在的所有目标,然后将新目标推入数组并存储。

    // const goals = localStorage.getItem("goals") || []; // you can declare here too.
    function addGoal() {
        const goals = localStorage.getItem("goals") || [];
        const userGoal = window.prompt("Enter goal:")
        goals.push(userGoal)
        localStorage.setItem('goals', JSON.stringify(goals)) // you need to transform into string
        ...
    

    然后您可以创建一个函数来渲染本地存储上的目标,例如:

    function renderGoals() {
        const goals = JSON.parse(localStorage.getItem("goals")); // parsing back
        // Then you can iterate on these goals (forEach for example) to render.
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-23
      • 2014-05-13
      • 2017-06-27
      • 1970-01-01
      • 2018-07-15
      • 2015-10-09
      • 2016-12-26
      • 2011-04-07
      相关资源
      最近更新 更多