【发布时间】:2017-07-21 08:42:38
【问题描述】:
我可以保存复选标记框的值,以便在刷新页面时它会相应地显示是否之前选中了该复选框?这是一个待办事项列表应用程序。我一直在搜索和阅读 MDN 文档试图找出解决方案,任何帮助将不胜感激。谢谢!
JavaScript
var masterList = [];
window.onload = function(){
masterList = JSON.parse(localStorage.getItem('masterList')); //get data from storage
if (masterList !== null) { //if data exist (todos are in storage)
masterList.forEach(function(task){ //append each element into the dom
var entry = document.createElement('li'); //2
var list = document.getElementById('orderedList'); //2
var text = document.createTextNode(task);
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'name';
checkbox.value = 'value';
checkbox.id = 'id';
entry.appendChild(checkbox);
document.getElementById('todoInput').appendChild(entry);
list.appendChild(entry);
entry.appendChild(text);
})
} else { //if nothing exist in storage, keep todos array empty
masterList = [];
}
}
function addToList(){
var task = document.getElementById('todoInput').value;
var entry = document.createElement('li'); //2
var list = document.getElementById('orderedList'); //2
var text = document.createTextNode(task);
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'name';
checkbox.value = 'value';
checkbox.id = 'id';
entry.appendChild(checkbox);
document.getElementById('todoInput').appendChild(entry);
list.appendChild(entry);
entry.appendChild(text);
masterList.push(task);
localStorage.setItem('masterList', JSON.stringify(masterList));
console.log(task);
console.log(masterList);
clearInput();
}
function clearInput() {
todoInput.value = "";
}
console.log((localStorage.getItem('masterList')));
编辑 - 添加其余代码 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1>To Do List:<h1>
<input id="todoInput" type="text">
<button type="button" onclick="addToList()">Add Item</button>
<ol id='orderedList'></ol>
<script src="todo.js"></script>
</body>
</html>
CSS
ol li {
background: lightgray;
text-align: left;
}
ol li:nth-child(odd){
background: lightblue;
text-align: left
text: 10%;
}
input[type=text]{
width: 20%;
border: 2px solid black;
background-color: rgba(255, 0, 0, 0.2);
text-align: center;
}
h1{
text-align: center;
}
【问题讨论】:
-
发布完整代码 (:
-
您可以使用
localStorage来保存复选框的值(假设浏览器允许)。请发布您的所有代码,以便我们查看哪些代码不起作用。 -
我已经发布了我所有的代码,我找不到保存复选框信息的起点。我是否必须创建一个新功能,还是我想将其添加到我已有的功能中?
-
请参阅this article 了解有关使用
localStorage的良好基础教程...它将向您展示如何设置和检索值。 -
@bemon 你得到了很好的答案还是我应该添加一个?
标签: javascript checkbox