【问题标题】:Printing localStorage values to the HTML page将 localStorage 值打印到 HTML 页面
【发布时间】: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


    【解决方案1】:

    在添加项目时更新listItemArraylocalStorage

    function addTask() {
        var input = document.getElementById('userTask');
        if (validate(input)) {
            listItemArray.push(input.value);
            storeListItems(listItemArray, 'todos');
            renderHtml(input.value);
        }
    }
    

    获取todos onload 并渲染它们

    function fetch(key, callback) {
        listItemArray = JSON.parse(localStorage.getItem(key));
        callback(listItemArray);
    }
    

    删除项目后更新listItemArraylocalStorage

    deleteTask.addEventListener('click', function() {
        var index = listItemArray.indexOf(val);
        listItemArray.splice(index, 1);
        storeListItems(listItemArray, 'todos');
        myUL.removeChild(addLi);
    });
    

    清空remove all上的列表

    function removeAll(myUL) {
        myUL.innerHTML = '';
        listItemArray = [];
        storeListItems(listItemArray, 'todos');
    }
    

    检查这个JS Bin

    【讨论】:

    • 感谢您的反馈!只是几个问题: 1. RenderHTML 函数和 inputValue createElement 的 val 参数从何而来?它只是一个占位符吗? 2. 我的全部删除按钮不起作用。如果我在 removeAll 函数中发出警报但将 UL 的 innerHTML 设置为空字符串似乎不再有任何作用,它会起作用。
    • 1. (a) val - 在页面加载时,我们从localStorage 获取待办事项,如果有的话,并使用renderHtml 函数渲染它们,所以这里val 指的是每个待办事项。 (b) 添加待办事项时,val 是用户输入的值(文本)。 2.请立即查看JSBin
    • 完全有道理!你的回答教会了我很多东西,现在我的目标是更多地了解回调等等。我还想我会制作一个迷你 localStorage 接口,我可以用我从这个应用程序中学到的东西将它实现到未来的项目中。干杯伙伴!
    • @Laere 很高兴我能提供帮助
    【解决方案2】:

    我已经修改了您的代码,以便它将当前在 listItemArray 中的所有内容保存到本地存储中,然后在页面加载后再次打印出该持久存储数组中的每个项目。

    事实证明,您实际上并没有将数组保存到本地存储中,因此每次调用 render() 函数时您都会得到 null。

    您会注意到我现在添加了这一行:storeListItems(listItemArray, 'todos'); 现在通过todos 键将数组(首先转换为字符串)正确存储到本地存储中。

    data.forEach 循环中的匿名函数定义指定了太多参数。你会注意到它现在只指定了一个参数,它代表当前作为循环迭代的一部分被访问的项目:

    function render(data) {
    
      data.forEach(function(currentItem) {
        console.log(currentItem);
      });
    
    }
    

    您可以在以下位置找到一个工作示例:http://codepen.io/anon/pen/xZEpqo?editors=001,您可以在其中使用浏览器内控制台(例如 Chrome 开发人员工具)查看打印输出。

    希望这会有所帮助。

    【讨论】:

    • 太棒了,帮了大忙。即使将参数之类的东西传递给函数,我还是很新。但这完全有道理。当我添加任务时,使用 args(listItemArray, key) 调用 Storelistitems 函数,它会将该输入添加到数组中。此外,如果没有其中的所有随机参数,forEach 匿名函数更有意义。我理解当前参数是指当前数组,然后记录它的内容。很好,谢谢!我其实理解你的变化:)!
    • 如何在刷新时将我记录的内容呈现到实际页面?用你的方法?
    猜你喜欢
    • 2016-03-26
    • 2016-12-05
    • 1970-01-01
    • 2012-04-07
    • 2011-11-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多