【发布时间】:2015-12-25 18:37:37
【问题描述】:
现在我有 5 个值存储到一个数组中,并且该数组存储在 localStorage 中。
我有一个需要 3 个参数的函数。数组、键名和解析本地存储中数组的回调函数。
我也有回调函数本身,它只是解析本地存储中的数组。
然后我有一个函数,它应该使用 forEach 函数将每个数组项呈现到页面,但是我不确定将什么放入实际的 forEach 函数本身。我尝试过传递诸如密钥之类的东西,我已经坚持了好几天了,虽然我一直在学习,但我仍然想将存储的数据打印到实际页面。
这是一个 JSBin:http://jsbin.com/monanoruno/edit?html,css,js,output
我的代码在这里:
window.onload = function() {
//global variables (global scope)
var warning = document.getElementById('warning');
var clear = document.getElementById('clear')
//array used for localstorage
var listItemArray = [];
var key = 'todos';
//this is where the party starts
fetch('todos', render);
clear.addEventListener('click', clearInput, false);
};
// create a function that adds task on user click button
function addTask() {
//variables within addTask scope
var addLi = document.createElement('LI');
var deleteTask = document.createElement('input');
var input = document.getElementById('userTask');
var inputValue = document.createTextNode(input.value);
var myUL = document.getElementById('myUL');
validate(input) //returns input or false
//define attributes of delete task button
deleteTask.setAttribute('type', 'submit');
deleteTask.setAttribute('value', 'X');
deleteTask.setAttribute('id', 'delete');
//event listener that toggles a 'crossout' effect for completed tasks
addLi.addEventListener('click', taskToggle, false);
//add the input value and delte task elements to the list item
addLi.appendChild(inputValue);
addLi.appendChild(deleteTask);
//add list element to ul element
myUL.appendChild(addLi);
//add the list item to an array
listItemArray.push(input.value);
//event that deletes single tasks
deleteTask.addEventListener('click', function(){
myUL.removeChild(addLi);
});
}
function validate(input) {
return input.value.length ? input : false
}
function storeListItems(listItemArray, key, fetch) {
var notes = JSON.stringify(listItemArray);
fetch(localStorage.setItem(key, notes));
}
function fetch(key, callback) {
callback(JSON.parse(localStorage.getItem(key)));
}
function render(data) {
data.forEach(function (current, index, array) {
});
}
//define clear button
function clearInput() {
var input = document.getElementById('userTask');
input.value = '';
}
//function removes all list elements created
function removeAll(myUL) {
//try while(myUL.firstChild) myUL.firstChild.remove()
myUL.innerHTML = '';
}
//define crossout function
function taskToggle(e) {
//li elements are targetted by the event object
var li = e.target;
//if li contains class remove, else add
if (li.classList.contains('crossOut')) {
li.classList.remove('crossOut');
} else {
li.classList.add('crossOut');
}
}
【问题讨论】:
标签: javascript arrays callback local-storage