【发布时间】: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