我正在使用javascript构建Todo应用,并且面临3个问题:
1.勾选列表后,在输入元素上设置选中属性。
<input type="checkbox" value="Go to Gym">
这句话错了吗?
checkbox.checked = data.status;
2)使用会话存储数据。
if(sessionStorage['task'] != null)
3)在UpdateJSON函数的dataJSON对象中,项目的状态(即选中或未选中)无法更新。
function updateJSON(event) {
let key = event.target.value;
dataJSON[key].status = event.target.checked;
sessionStorage['task'] = JSON.stringify(dataJSON);
}
var output = document.querySelector('#output'),
taskList = document.querySelector('#taskList'),
html = '',
dataJSON='';
document.querySelector('#myForm').addEventListener('submit', function(e) {
e.preventDefault();
var userInput = document.querySelector('input[name="task"]'),
tempValue = userInput.value;
console.log(tempValue);
userInput.value = '';
console.log(dataJSON);
addNewElement({"info": tempValue,"status": false})
});
//console.log(data);
window.onload = function(){
if(sessionStorage['taskList'] != null){
dataJSON = JSON.parse(sessionStorage['task']);
} else {
var data = '[{"info":"Cut Grass","status":true},{"info":"Clear Roo","status":false},{"info":"Go to Gym","status":true},{"info":"Make dinner","status":false}]';
dataJSON = JSON.parse(data);
}
buildCheckboxesData(dataJSON);
};
function addNewElement(data) {
addCheckbox(data, data.length);
dataJSON.push(data);
}
function addCheckbox(data, key) {
var li = document.createElement('li');
var checkbox = document.createElement('input');
var textNode = document.createTextNode(data.info);
checkbox.type = 'checkbox';
checkbox.value = data.info;
checkbox.checked = data.status;
checkbox.onchange = updateJSON;
li.appendChild(textNode);
li.appendChild(checkbox);
taskList.appendChild(li);
}
function buildCheckboxesData(data){
for(let key in data){
addCheckbox(data[key], key)
}
}
function updateJSON(event) {
let key = event.target.value;
dataJSON[key].status = event.target.checked;
sessionStorage['taskList'] = JSON.stringify(dataJSON);
}
<div id="output">
<ul id="taskList"></ul>
</div>
<form id="myForm" action="">
Task: <input type="text" name="task" placeholder="add task">
<button type="submit">Add new Task</button>
</form>