我可以保存複選標記框的值,因此當頁面刷新時,如果在之前檢查過框,它會相應顯示嗎?這是一個待辦事項列表應用程序。我一直在尋找和閱讀MDN文件試圖找出解決方案,任何幫助將不勝感激。謝謝!在頁面刷新時使用JavaScript保存複選標記
的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'保存複選框的值(假設瀏覽器允許)請發表您的所有代碼,所以我們可以看到 – freginold
我已經發布了所有的代碼,我找不到保存複選框信息的起點。我是否需要創建一個新的函數,還是我想要添加到已有的東西中? – bemon